hdu1018

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 Input2
10
20
Sample Output7
19
Source Asia 2002, Dhaka (Bengal)
方法一:求1+(int)log10(n!)=1+log10(1)+log10(2)+……+log10(n)
注意遍历过程中是double,到最后再取整。

#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    long long n,a,i;
    double m;
    scanf("%lld",&n);
    while(n--)
    {
        scanf("%lld",&a);
        m=0;
        for(i=2;i<=a;i++)
            m+=log10(i);
        cout<<(int)m+1<<'\n';
    }
    return 0;
}

方法二:斯特林近似值公式:在这里插入图片描述
求阶乘有多少位,即log10(n!)

#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
const double pi=acos(-1.0);
int main()
{
    long long n,a,i;
    double m;
    scanf("%lld",&n);
    while(n--)
    {
        scanf("%lld",&a);
        m=0.5*log10(2*pi*a)+a*log10(a/exp(1));
        cout<<(int)m+1<<'\n';
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43871207/article/details/87925417