Big Number

来源:互联网 发布:免安装的mysql怎么配置 编辑:程序博客网 时间:2024/05/02 13:06

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1018


Big Number



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 ≤ 107 on each line.
 
Output
The output contains the number of digits in the factorial of the integers appearing in the input.
 
Sample Input
21020
 
Sample Output
719

题目大意:
    有多组测试例,第一个数为n,表示有n组测试例。接下来有n行,每行有一个整数m,要求你就出m的阶乘的位数,比如10的阶乘为3628800,是一个七位数,那么按题目要求输出7即可...
 
N的阶乘:N!=1*2*3....*n  要 求N!的位数,那么我们很自然想到对一个数取对数,
即 log10(n!)=log10(1)+ log10(2) +log10(3)...+log10(n)
做这题的时候,第一次提交代码超时了,其实我写完代码就感觉会超时,不过还是提交了一下,果然超时了。我是用C++写的,这里也分享一下。为什么超时了还分享呢,因为同样的代码,只要改成C的写法提交就AC了,不过也挺险的,用了968毫秒,差点就超时了,呵呵。
 
超时代码是这样的:

#include<iostream>#include<cmath>using namespace std;int main(){ int n; cin>>n; while(n--) {  int m;  double sum=0;  cin>>m;  for(int i=1; i<=m; i++)   sum = sum + log10(i);  cout<<(int)sum+1<<endl; } return 0;}

修改后AC的代码是这样的:

#include<stdio.h>#include<math.h>int main(){ int n; scanf("%d",&n); while(n--) {  int m;  double sum=0;  scanf("%d",&m);  for(int i=1; i<=m; i++)   sum = sum + log10(i);  printf("%d\n",(int)sum+1); }}

这里还有一种算法也AC了,代码是别人的:
要用到组合数学的知识(log10(n!) = log10(sqrt(2 * pi * n)) + n * log10(n / e))

#include<iostream>#include<cmath>using namespace std;#define PI 3.14159265int num,ans;void solve(){ double t; int i; t = (num*log(num)-num+0.5*log(2*num*PI))/log(10); ans = t+1; cout<<ans<<endl;}int main(){ int n; while(cin>>n) {  while(n--)  {   cin>>num;   solve();  } } return 0;} 












原创粉丝点击