求大数的阶乘的位数:PKU :1423:Big Number

题目描述:

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 <= m <= 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个数,每个数m都可能很大,要求输出m!的位数,比如说10!=2628800,那么输出就是7。
解法一(该方法在PKU上会TLE,原因是其复杂度为o(n) ):
由于n!=n*(n-1)*……*2*1 = 10^dn * 10^dn-1 *……* 10^di*……10^d0 = 10^(dn+dn-1+……+d0);其中:dn = log10(n),dn-1 = log10(n-1)……
因此,n!的位数其实就是dn+……+di+……+d0;因此可以得到如下代码:
#include "iostream"
#include "cmath"
using namespace std;
int main(int argc, char* argv[])
{
 int N;
 int Num;
 cin>>N;
 double d  ;
 for (int i =0;i<N;i++)
 {
  cin>>Num;
  d =1;
  for (int j=2;j<=Num;j++)
  {
   d +=log10(j);
  }
  cout<<(int)d<<endl;
 }
 
 return 0;
}
解法二:stirling公式,复杂度O(1),PKU上通过
假设n! = 10^d;其中d可能包含小数,但是d的整数部分就是n!的位数
由stirling公式:n!~((n/e)^n )* (2* pi * n)^(1/2);则: d = log10(n!) = n*log10(n/e) + 0.5*log10(2*pi*n);于是得到如下代码:

#include "iostream"
#include "cmath"
using namespace std;
const double pi = 3.1415926535898;
const double e = 2.718281828459;
int main(int argc, char* argv[])
{
 int N;
 int Num;
 cin>>N;
 for (int i =0;i<N;i++)
 {
  cin>>Num;
  cout<<(int)(Num*log10(Num / e) + 0.5*log10(2*pi*Num)) +1<<endl;
 }
 
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值