HDU 1018 Big Number(斯特林公式)

Big Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


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 ≤ 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!的位数,比如说10!=3628800,故10!的位数为7

解题思路:该题有两种解法,一种稍微暴力一点,另一种则是需要知道公式才可以解

首先,不管是暴力的方法还是通过公式计算的方法,都涉及到了之前提及过的一种方法,即通过以10为底取对数后,取整加1即为该数的位数,我们不妨理理思路,思考一下该方法是怎么得到的

第一步,假设N!= k,那么


k的以10为底的对数值必定可以表示成A.B的形式,A为结果的整数部分,B为小数部分

这样的话


我们依旧拿10!来举例,它的A=6,B=0.559763033…,这个自己计算一下就会知道的,

可得

我们只需计算出A的值,结果就是A+1

接下来则是计算N!

可以边暴力边计算位数,因为


for(i=1;i<=n;i++)
    sum+=log10((double)i);
也可以直接利用斯特林公式


#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<stdlib.h>
#include<cmath>
#include<string>
#include<algorithm>
#include<iostream>
#define exp 1e-10
using namespace std;
const int N = 105;
const int inf = 2147483647;
const int mod = 2009;
int main()
{
    int t,n;
    double ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        ans=0.5*log10(2*n*acos(-1.0))+n*log10(n*1.0)-1.0*n/log(10.0);
        printf("%d\n",int(ans)+1);
    }
    return 0;
}
菜鸟成长记


你可能感兴趣的:(ACM,斯特林公式)