ACM : 一道基础数学题目POJ 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!的位数 (注意:n的范围很大 可达到10^7)

解题思路:计算结果出来很明显只有超时下场. (10^6 PC机约用 1 second)

          1.想到求一个数的位数可以用log10(n) , 对这个结果进一法就可以得到结果.

          2.如果求一个数的阶乘的位数log10(n!) , 但是输入的数字很大. 根据对数一个

          性质:log10(n!) = log10(1) + log10(2) + ...... + log10(n-1) + log10(n)

          3.可以递推一下: log10( (2n) ! ) = log10(n!) + log10(n+1) + .... + log10(2n)

          4.太好了...递推结果出来了~打表吧. 

 

启发:  n! 可以用斯特林公式. (忘记了! 推导吧.)

          n! = 1 * 2 * 3 * ... * n

          两边取对数ln: ln n! = ln1 + ln2 + ln3 + ... + lnn

       ln n! = ∑lnk (k = 1,2,3,...,n)

       ln n! = ∫(n~1) lnxdx + 1 / 2 (ln2 - ln1 + ln3 - ln2 + ...+lnn - ln(n-1))

           = n*lnn + 1/2lnn - n + 1

(∫(n~1):积分上限是n , 下限是1)

      n! ≈ (n^n) * (n^(1/2)) * (e^-n) * (e^-1)

          ≈ (n/e)^n * sqrt(2*π*n)                           (2*π ≈ e^2) 

 

AC代码:

#include <cstdio>
#include <iostream>
#include <math.h>
using namespace std;
#define PI 3.141592653589793239
#define e 2.718281828459

int main()
{
      int n;
 //  freopen("a.txt","r",stdin);

      scanf("%d",&n);
     while(n--)
    {
          int dig;
          scanf("%d",&dig);
          double result =  log10( sqrt(2 * PI * dig)) + dig * log10(dig / e);
          printf("%d\n", (int)result + 1 );
     }

     return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值