hdu 1018 Big Number

hdu 1018 Big Number

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 不大,就可以用暴力算法,将 n ! 求出来,然后在计算位数,然而 这题的 n 很大,用暴力求解会超时。
刚开始我就用暴力方法求解,然而超时,这里还是给出暴力求解的代码
暴力方法求解,超时代码:

#include <algorithm>
#include<string.h>
#include<math.h>
int n;
int ans[100000];
using namespace std;
int main()
{
    scanf("%d",&n);
    while (n--)
    {
        int num;
        scanf("%d",&num);
        memset(ans,0,sizeof(ans));
        ans[1] = 1;
        int k = 1;
        int i;
        int j;
        int one = 0;
        for (i=1;i<=num;i++)
        {
            for (j=1;j<=k;j++)
            {
                int t = ans[j] * i + one;
                ans[j] = t % 10;
                one = t / 10;
            }
            while (one)
            {
                ans[j] = one % 10;
                one = one / 10;
                j++;
            }
            k = j - 1;
        }
        printf("%d\n",k);
    }
  }
    return 0;
}

这里补充一种快速求一个整数的位数的方法:

#include<stdio.h>
#include <iostream>
#include <algorithm>
#include<string.h>
#include<math.h>
int n;
int ans[100000];
using namespace std;
int main()
{
    scanf("%d",&n);
    while (n--)
    {
        int num;
        scanf("%d",&num);
        int ans = log10(num) + 1;	//快速求一个整数的位数的方法
        printf("%d\n",ans);
    }
  }
    return 0;
}

这里补充一个求阶乘的近似值公式:
斯特林公式(Stirling’s approximation)
是一条用来取n的阶乘的近似值的数学公式。一般来说,当n很大的时候,n阶乘的计算量十分大,所以斯特林公式十分好用,而且,即使在n很小的时候,斯特林公式的取值已经十分准确。

在这里借用别人的分析:
在这里插入图片描述
给出代码:

#include<stdio.h>
#include <iostream>
#include <algorithm>
#include<string.h>
#include<math.h>
int n;
int ans[100000];
using namespace std;
int main()
{
    scanf("%d",&n);
    while (n--)
    {
        int num;
        scanf("%d",&num);
        double sum = 0;		//注意这里的用双精度浮点型,不然数据会损失
        for (int i=1;i<=num;i++)
            sum += log10(i);
        printf("%d\n",int(sum)+1);	//强制转换为int 型
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43557810/article/details/87924959