题目大意:求n!的结果的位数n<=10^7
思路:
首先要求一个数字有多少位,可以用(int)log10(num)+1,这样就求出num有多少位
哎用log10()函数的结果最后要+1~因为运算的时候有精度缺失~不是很懂~~怪不得我之前都没得结果,只能先记一下了。囧。。
更坑爹的是:要不是我在线打表的话,铁定无限TIE~~~囧。。
program1:(在线打表)
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
double mm[8000000];
int main()
{
mm[0]=0;
for(int i=1;i<=8000000;i++)
{
mm[i]=log10((double)i)+mm[i-1];
}
/*for(int i=1;i<=30;i++)///
{
printf("%I64d ",(__int64)mm[i]+1);
}*/
int n,test;
scanf("%d",&test);
while(test--)
{
scanf("%d",&n);
if(n<=8000000)
printf("%I64d\n",(__int64)mm[n]+1);///
else
{
double tmp=mm[8000000];
for(int i=8000001;i<=n;i++)
tmp+=log10((double)i);
printf("%I64d\n",(__int64)tmp+1);
}
}
//system("pause");
return 0;
}
program2:(公式法秒杀)
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int n,test;
scanf("%d",&test);
while(test--)
{
scanf("%d",&n);
double e=exp(1.0);
double pi=acos(-1.0);
double r=0.5*log10(2.0*pi*n)+n*log10((double)n/e);
//double r=log10(sqrt(2 * pi * n)) + n * log10(1.0*n / e);
printf("%I64d\n",(__int64)r+1);
}
//system("pause");
return 0;
}
公式参考博客:http://blog.sina.com.cn/s/blog_4c8a2a870100kvxp.html
《The art of computer programming》中,1或2章:
n! = sqrt(2*π*n) * ((n/e)^n) * (1 + 1/(12*n) + 1/(288*n*n) + O(1/n^3))
π = acos(-1)
e = exp(1)
=》log10(1 + 1/(12*n) + 1/(288*n*n) + O(1/n^3)) ≈ log10(1) = 0 ---(1)
=》
log10(n!) = log10(sqrt(2 * pi * n)) + n * log10(n / e)
结果要加上1,因为约掉了(1)式