杭电1018—大数阶乘位数计算
http://acm.hdu.edu.cn/showproblem.php?pid=1018
Big Number
Time Limit: 2000/1000 MS(Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s):17850 Accepted Submission(s): 8006
Problem Description
In many applications very large integersnumbers are required. Some of these applications are using keys for securetransmission 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 integernumbers. The first line contains an integer n, which is the number of cases tobe tested, followed by n lines, one integer 1 ≤ n ≤ 107 on each line.
Output
The output contains the number of digits inthe factorial of the integers appearing in the input.
Sample Input
2
10
20
Sample Output
7
19
看到这个题目,觉得就是大数阶乘问题,只需将大数输入进数组,然后模拟手算一位一位计算即可。
这是我之前的代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
int carry,n,j;
int a[40001];
int digit;
int temp,i;
int T;
cin>>T;
while(T--)
{
scanf("%d",&n);
a[0]=1;digit=1;
for(i=2; i<=n; i++)
{
for(carry=0,j=1; j<=digit; ++j)
{
temp=a[j-1]*i+carry;
a[j-1]=temp%10;
carry=temp/10;
}
while(carry)
{
//digit++;
a[++digit-1]=carry%10;
carry/=10;
}
}
printf("%d\n",digit);
}
return 0;
}
提交后发现TLE,顿时醒悟,这题要用到斯特拉公式计算位数,以后碰到计算阶乘位数的时候,基本上可以用到该公式:
log10(n!)=log10(1*2*3…*n)=log10(1)+log10(2)+…+log10(n)
这样,代码经过修改后,短小精悍,时间复杂度o(N),顺利AC!
修正后的代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
//log10(n!)=log10(1*2*3…*n)=log10(1)+log10(2)+…+log10(n)
//斯特林公式://log10(n!)=(0.5*log(2*PI*n)+n*log(n)-n)/log(10)
int main()
{
int i,n;
double ca;
int T;
cin>>T;
while(T--)
{
cin>>n;
ca=0;
for(i=1;i<=n;i++)
ca+=log10(double(i));
cout<<int(ca)+1<<endl;
}
return 0;
程序运行结果: