N!阶乘是一个非常大的数,大家都知道计算公式是N!=N*(N-1)······*2*1.现在你的任务是计算出N!的位数有多少(十进制)?
- 输入
-
首行输入n,表示有多少组测试数据(n<10)
随后n行每行输入一组测试数据 N( 0 < N < 1000000 ) - 输出
- 对于每个数N,输出N!的(十进制)位数。
- 样例输入
-
3 1 3 32000
- 样例输出
-
1 1 130271
题解一:直接利用斯特林公式
s=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 );(n>1)
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int t,n,s;
cin>>t;
while(t--)
{
cin>>n;
if(n==1)
cout<<"1"<<endl;
else
{ s=(long)( (log10(sqrt(4.0*acos(0.0)*n)) + n*(log10(n)-log10(exp(1.0)))) + 1 );
cout<<s<<endl;
}
}
return 0;
}
然后利用for循环求m的值(n值过大可能会超时)
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
int m,s;
double t=1;
cin>>m;
for(int i=1;i<=m;i++)
t=t+log10(i);
s=(int)t;
cout<<s<<endl;
}
return 0;
}