第一种:
lg(N!)=[lg(N*(N-1)*(N-2)*......*3*2*1)]+1
=[lgN+lg(N-1)+lg(N-2)+......+lg3+lg2+lg1]+1
代码
#include#include int main() { int n; double sum=0; scanf("%d",&n); for(int i=1;i<=n;i++) { sum = sum+log10(i); } printf("%d\n",(int)sum+1); return 0; }
第二种:
用Stirling公式计算n!结果的位数时,可以两边取对数,得:
log10(n!) = log10(2*PI*n)/2+n*log10(n/E);
故n!的位数= log10(2*PI*n)/2+n*log10(n/E)+1(注意:当n=1时,算得的结果为0)
代码
#include#include #define PI 3.141592654 #define E 2.71828182846 int main() { int n,sum=1; scanf("%d",&n); if(n>3) sum=log10(2*PI*n)/2+n*log10(n/E)+1; printf("%d\n",sum); return 0; }
(2)阶乘计算
#includeint num[1000000]; int main() { int i,j,sum; int temp,digit,n; scanf("%d",&n); num[0] = 1; digit = 1; for(i=2;i<=n;i++) // 从2开始乘 { sum = 0; for(j=0;j = 10 { num[digit] = sum % 10; // 继续将数存到数组中 sum /= 10; digit++; } } for(i=digit-1;i>=0;i--) printf("%d",num[i]); putchar('\n'); }
Comments | NOTHING