HDU1018(斯特林公式)

来源:互联网 发布:中国国家地理 知乎 编辑:程序博客网 时间:2024/04/29 09:49

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
21020
 

Sample Output
719
这个题的意思是:给你一个数,让你求出N!由多少位数构成,比如输出10,它的阶乖是3628800 由7位数构成,这时你要输出7;
解题思路:
1.可以暴力,N的阶乖的位数等于LOG10(N!)=LOG10(1)+.....LOG10(N);
2.Stirling公式:n!与√(2πn) * n^n * e^(-n)的值十分接近
故log10(n!) = log(n!) / log(10) = ( n*log(n) - n + 0.5*log(2*π*n))/log(n);
解法一:
LANGUAGE:C++
CODE:
[html] view plain copy
print?
  1. #include<stdio.h>  
  2. #include<math.h>  
  3. double reback(int n)  
  4. {  
  5.     double cnt=0;  
  6.     for(int i=2;i<=n;i++)  
  7.     {  
  8.         cnt+=log10(i);  
  9.     }  
  10.     return cnt;  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     int cas,n;  
  16.     scanf("%d",&cas);  
  17.     while(cas--)  
  18.     {  
  19.         scanf("%d",&n);  
  20.         printf("%d\n",(int)reback(n)+1);  
  21.     }  
  22.     return 0;  
  23. }  

解法二:
LANGUAGE:C++
CODE:
[html] view plain copy
print?
  1. #include <stdio.h>  
  2. #include <math.h>  
  3.   
  4. const double PI = acos(-1.0);  
  5. const double ln_10 = log(10.0);  
  6.   
  7. double reback(int N)  
  8. {  
  9.     return ceil((N*log(double(N))-N+0.5*log(2.0*N*PI))/ln_10);  
  10. }      
  11.   
  12. int main()  
  13. {  
  14.     int cas,n;  
  15.     scanf("%d",&cas);  
  16.     while(cas--)  
  17.     {  
  18.         scanf("%d",&n);  
  19.         if(n<=1)printf("1\n");  
  20.         else printf("%.0lf\n",reback(n));  
  21.     }  
  22.     return 0;  
  23. }  


原创粉丝点击