Source: http://www.cnblogs.com/stonehat/p/3603267.html
Here, worship the original author hehe
We know that the number of bits of integer n is calculated as: log10 (n) +1
So the number of n! is log10 (n!) +1
If the specific value of n! is required, the calculation will be very slow for a large n (for example, n=1000000), and if only the number of digits of the factorial is obtained, the Stirling (Stirling) formula can be used to solve
Sterling (Stirling) formula:
So the number of n! is to seek log10 ((2*pi*n) ^1/2* (n/e) ^n) +1
namely 1/2*log10 (2*pi*n) +n*log10 (n/e) +1
So using the following code to calculate the number of factorial digits, it will be very fast
1 #definePI 3.1415926542 #defineE 2.718281828463 intLintN)4 {5 ints=1;6 if(n>3)7S=LOG10 (2*PI*N)/2+N*LOG10 (n/e) +1;8 returns;9}
If you want to calculate the exact value of a factorial, you can use the following code.
1 /*2 function Function: calculates and outputs the factorial of n3 return Value: The number of digits of the factorial result4 Note:5 This program directly output n! results, need to return the results please keep long a[]6 need math.h7 */8 9 intFactorial (intN)Ten { One Longa[10000]; A inti,j,l,c,m=0, W; -a[0]=1; - for(i=1; i<=n;i++) the { -C=0; - for(j=0; j<=m;j++) - { +a[j]=a[j]*i+C; -c=a[j]/10000; +a[j]=a[j]%10000; A } at if(c>0) {m++;a[m]=C;} - } - -w=m*4+LOG10 (A[m]) +1; -printf"\n%ld", A[m]); - for(i=m-1; i>=0; i--) printf ("%4.4ld", A[i]); in returnW; -}
The number of digits and exact values of a large number of factorial calculations "go"