题意,给一个n(<10^7)
求n!的最高位数字
比如3!=6 最高位就是6
解法:
lgn!=lg1+lg2+....+lgn=temp
这里如果用O(n)的累加算lgn!就会因为样例数可能达到1000个
10^7*10^3>10^8而超时
有斯特林公式
lgn!=log10(sqrt(2*PI*n*1.0))+n*log10(n*1.0/e)
算出lgn!后,比如对于
n=5
lg5!=2.07918
由于整数部分与最高位无关
剪掉变成0.07918
10^0.07918=1.19999
于是最高位就是1
由于斯特林公式在n比较小的时候误差较大,所以在n较小时可以用O(n)的方法算lgn!
上代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<math.h>
using namespace std;
#define PI acos(-1.0)
#define e exp(1.0)
int main()
{
int total;
scanf("%d",&total);
while(total--)
{
int n;
scanf("%d",&n);
double temp;
if(n>1000)
{
temp=log10(sqrt(2*PI*n*1.0));
temp+=n*log10(n*1.0/e);
}
else
{
temp=0;
for(int i=1;i<=n;i++)
{
temp+=log10(i*1.0);
}
}
temp-=(int)temp;
temp=pow(10.0,1.0*temp);
printf("%d\n",(int)temp);
}
return 0;
}