数的长度
-
描述
-
N!阶乘是一个非常大的数,大家都知道计算公式是N!=N*(N-1)······*2*1.现在你的任务是计算出N!的位数有多少(十进制)?
#include <stdio.h>
#include <math.h>
int weishu(int m)
{
int i,j;
for(i=1; ;i++)
{
j=pow(10,i);
if(m/j==0)
break;
} //判断一个数的位数
return i;
}
int jiechen(int n)
{
if(n>1) return n*jiechen(n-1);
else return 1; //递归求出阶乘
}
int main()
{
int n,x,y,z;
scanf("%d",&n);
while(n--)
{
scanf("%d",&x);
y=jiechen(x);
z=weishu(y);
printf("%d\n",z); //此方法无法解决大数。 但是一定数据内可以实现题目要求,所以我看了下评论区 看到了斯特林公式
}
return 0;
}
如下:
#include <stdio.h>
#include <math.h>
int main()
{
int n,i,x;
double s;
scanf("%d",&n);
while(n--)
{
s=0;
scanf("%d",&x);
for(i=1;i<=x;i++)
s+=log10(i); //斯特林公式 求N!的位数等于lnN! +1
//http://blog.csdn.net/liangzhaoyang1/article/details/51145807
printf("%d\n",int(s+1));
}
}