Big Number

题目链接: 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 ≤ 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

题目大意:
    有多组测试例,第一个数为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.14159265
int 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;
} 












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值