第一种是暴力的解法,注意,不是本质的暴力,只是相对的暴力:
设K为一个整数N的位数长度,则:K = log(N)+1; eg.3 < log(1000~9999)<4;
因为N! = 1 * 2 * 3 * 4 * 5 *……*N;
log(N!) = log(1 * 2 * 3 * 4 * 5 *……*N)
=log1 + log2 + log3 + …… + logN:
#include<iostream> #include<cmath> using namespace std; int main() { int n,num,i; double result; for(scanf("%d",&n);n;--n) { scanf("%d",&num); result=1; for(i=1;i<=num;++i) result+=log10(double(i)); printf("%d\n",int(result)); } return 0; }
第二种:
Stirling定理:http://baike.baidu.com/view/2019233.htm?fr=ala0_1
n! = sqrt(2*π*n) * ((n/e)^n)
得到公式 log10(n!) = log10(sqrt(2 * pi * n)) + n * log10(n / e) + 1
#include<cstdio> #include<cmath> const double PI=acos(-1.0),e=exp(1.0); int main() { int t,n; scanf("%d",&t); while(t--) { scanf("%d",&n); printf("%d\n",(int)(log10(sqrt(2*PI*n))+n*log10(n/e))+1); } return 0; }