您的位置:首页 > 其它

HDU 1018 Big Number

2016-05-28 13:42 405 查看

Big Number

[align=center]Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
[/align]
[align=center]Total Submission(s): 34053    Accepted Submission(s): 16100
[/align]

[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
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 ≤ 107 on each line.

 

[align=left]Output[/align]
The output contains the number of digits in the factorial of the integers appearing in the input.

 

[align=left]Sample Input[/align]

2
10
20

 

[align=left]Sample Output[/align]

7
19

题目分析:大体上就是先输入一个整数N,然后分别再输入N个整数,分别判断每一个整数的阶乘有多少位,比如输入10,10!=3628800,这个数一共有7位,因此输出7;

当然,这道题目肯定不能直接求出数的阶乘再判断位数,这样会溢出的,下面我用了两种方法来求,都实现了AC,先介绍第一种:

采用斯特林公式求解:

(斯特林公式:lnN!=NlnN-N+0.5*ln(2*N*PI))求出位数即可,还是要注意一下输出格式哦!贴代码:

#include<iostream>
#include<math.h>
using namespace std;
#define PI 3.1415926535
int main()
{
int T;//记录每一块
int result; //记录下结果
cin>>T;
while(T--)
{
int n;
double t;
cin>>n;
t=(n*log(n)-n+0.5*log(2*n*PI))/log(10);
result=(int)t+1;
cout<<result<<endl;
}
return 0;
}


当然了,用这种方法求解的前提要先知道这个数学公式,老实说我也是百度之后才知道的,不知道的人拿到手肯定无法用这种方法来做了,那就用第二种方法,这种方法学过对数的童鞋都应该会吧0.0!
lnN!=lnN+ln(N-1)+ln(N-2)+ln(N-3)......+ln2+ln1;

用循环求得1~N的对数和lnN!,然后[lnN!],取对数和的上整数就可以了,这种方法也很简单。贴AC代码:

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int T;//记录每一块
cin>>T;
while(T--)
{
int n;
double t=0.0;
cin>>n;
for(int i=1;i<=n;i++)
{
t+=log(i)/log(10);
}
  cout<<(int)t+1<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: