階乘(斯特林定理)

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
2 10 20
 

Sample Output
7 19
 

題意大意:輸入n,問n的階乘是幾位數。
解題思路:這題n的範圍最大到107,所以肯定不能用常規的方法求n!,甚至可能沒有必要求。在這裏,我要介紹一下斯特林定理(粗略介紹)。
具體公式:n!≈√(2πn)(n/e)n

我們對等號兩邊同時取以10爲底的對數,則可得:(設k爲n!的位數)

k-1 =log10(n!)= log10(√(2πn))+nlog10(n/e)

k爲什麼要減1呢?很簡單,log10(10) = 1,但是10是兩位數,所以我們所求的位數與實際相差1.

輔助知識:

log10(a*b) = log10(a) + log10(b)

log10(a/b) = log10(a) - log10(b)


源代碼如下:
#include<cstdio>
#include<cmath>
using namespace std;
#define Pi 3.14159265
#define e 2.71828182
int main(void)
{
    int cas,n;
    double digit;
    scanf("%d",&cas);
    while(cas--)
    {   scanf("%d",&n);
        digit = log10(sqrt(2*Pi*n))+n*log10(n/e);//斯特林定理的應用
        printf("%d\n",(int)digit+1);        //把上面k-1的1移到等式右邊就是加1
    }

    return 0;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章