题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1018
Big NumberTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 25856 Accepted Submission(s): 11743
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
Sample Output
|
求n!的位数,转化成求log10(n!)的问题;
1,直接求解,log10(n!)=log10(1)+log10(2)+...+log10(n)
2,利用斯特林公式 : log10(n!)=1.0/2*log10(2*pi*n)+n*log10(n/e)
3,打表
不用公式的 :900ms+;
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
int a;
scanf("%d",&a);
double sum = 0 ;
int i;
for(i=1;i<=a;i++)
sum += log10(i);
printf("%d\n",(int)(sum+1));
}
return 0;
}
用公式求的:0ms;
#include <stdio.h>
#include <math.h>
#define E 2.71828182845904523536028747135266250
#define PI 3.141592654
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
int a;
scanf("%d",&a);
double sum =(double) 0.5*log10(2*PI*a)+a*log10(a*1.0/E);
printf("%d\n",(int)(sum+1));
}
return 0;
}
打表:
#include<stdio.h>
int main()
{
int n,m,i,bit=1;
double num=0;
scanf("%d",&n);
while(n--)
{
bit=1,num=1;
scanf("%d",&m);
for(i=2;i<=m;i++)
{//num只是转化为整数部分有1位,其余的都在小数部分,防止方法溢出
num*=i;
if(num<10){continue;}
if(num<100){num/=10;bit+=1;continue;}
if(num<1000){num/=100;bit+=2;continue;}
if(num<10000){num/=1000;bit+=3;continue;}
if(num<100000){num/=10000;bit+=4;continue;}
if(num<1000000){num/=100000;bit+=5;continue;}
if(num<10000000){num/=1000000;bit+=6;continue;}
if(num<100000000){num/=10000000;bit+=7;continue;}
}
printf("%d\n",bit);
}
return 0;
}