数的长度
原题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=69
分析:先看看求n!的朴素算法,用大整数乘法来实现。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int wei[];
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
memset(wei,,sizeof(wei));
int cnt=;
scanf("%d",&n);
wei[cnt]=;
for(int i=;i<=n;i++)
{
int carry=;
for(int j=;j<=cnt;j++)
{
int t=carry;
carry=(wei[j]*i+t)/;
wei[j]=(wei[j]*i+t)%;
}
if(carry)
{
wei[++cnt]=carry;
wei[cnt]=carry%;
carry/=;
}
while(carry>=)
{
wei[++cnt]=carry%;
carry/=;
}
if(carry)
wei[++cnt]=carry;
}
printf("%d\n",cnt+);
}
return ;
}
分析:设n!=10^M,则log10(n!)=M=log10(1)+log10(2)+……,然后向上取整即可!
也可以直接套公式!n!的位数 = log10(2*PI*n)/2+n*log10(n/e)。或者 = log10(sqrt(2*PI*n)) + n*log10(n/e)。
stirling公式证明: http://episte.math.ntu.edu.tw/articles/mm/mm_17_2_05/index.html
附:PI=acos(-1.0)=2acos(0.0).
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int fac[];
void wei(int n)
{
double M=;
fac[]=;
fac[]=;
for(int i=;i<=n;i++)
{
M+=log10(i);
if(M-(int)M!=)
fac[i]=(int)M+;
else
fac[i]=(int)M;
}
}
int main()
{
wei();
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("%d\n",fac[n]);
}
return ;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define pi acos(-1.0)
using namespace std;
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
double ans=(log10(*pi*n))/+n*log10(n/exp(1.0));
printf("%d\n",(int)ans+);
}
return ;
}