Problem Description
In many applications very large integers numbers are required. Some of these applications are using keys for secure transmission of data, encryption, etc. In this problem you are given a number, you have to determine the number of digits in the factorial of the number.
Input
Input consists of several lines of integer numbers. The first line contains an integer n, which is the number of cases to be tested, followed by n lines, one integer 1 ≤ n ≤ 10
7 on each line.
Output
The output contains the number of digits in the factorial of the integers appearing in the input.
Sample Input
2 10 20
Sample Output
7 19
依旧是水题,但是这道题的数据很大,(1 ≤ n ≤ 107),这种情况即使用数组存时间也很长,于是我们来看看里面的规律:
我们知道,一个自然数n的位数用lg(n)+1计算,所以n!的位数即lg(n!)+1=lg(n*(n-1)*(n-2)....*3*2*1)+1=(lg(n)+lg(n-1)+...+lg(3)+lg(2)+0)+1;
PS:本题还用另一种更为优化的方法:斯特林公式! 数学还真是重要啊:这里附上斯特林公式的证明链接:斯特林公式
附上代码:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int n,a,i;
double lenth;
cin>>n;
while(n>0)
{
cin>>a;
lenth=0;
for(i=1;i<=a;i++)
{
lenth+=log10(i);
}
cout<<(int
)lenth+1<<endl;
n--;
}
return 0;
}
靡不有初,鲜克有终!千里之行,始于足下!