#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
const int max=3000;
int f[3000];
int main()
{
int i,j,n;
scanf("%d",&n);
memset(f,0,sizeof(f));
f[0]=1;
for(i=2;i<=n;i++) //从i乘到n
{
int c=0;
for(j=0;j<3000;j++) //每一位在乘法时的调整
{
int s=f[j]*i+c;
f[j]=s%10;
c=s/10;
}
}
for(j=3000-1;j>=0;j--)
if(f[j]) break;
for(i=j;i>=0;i--)
cout<<f[i];
return 0;
}
I want to write a comment to help myself understand, but I can’t continue writing halfway through. Why are the three lines in the middle of for written like that?
It seems to be just an ordinary vertical calculation of multiplication, there’s nothing much to say
Since multiplication will exceed int or even long long, high precision is required.
The idea of high precision is to use an array to store each digit of the number, and then simulate the vertical multiplication method of human calculation of multiplication.
You can consider how to calculate an array a of length n times a number x, assuming that a is stored from low to high (for example, the number 12345, the array is a[1]=5,a[2]=4,a [3]=3,a[4]=2,a[5]=1).
First of all, everyone is a[1]x%10, but what is the tens digit? It should be (a[2]x+carry of the previous digit)%10
So here, c represents the carry of the previous digit. , f[j] represents the j-th bit of (i-1)! before looping to j, and after looping to j, it represents the j-th bit of i!.