Big number
Time Limit: 2000/1000 MS (Java/others) memory limit: 65536/32768 K (Java/Others)
Total submission (s): 25649 accepted submission (s): 11635
Problem descriptionin response 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.
Inputinput 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 ≤0 ≤ 107 on each line.
Outputthe output contains the number of digits in the factorial of the integers appearing in the input.
Sample input21020
Sample output719
Sourceasia 2002, Dhaka (Bengal)
Recommendjgshining
I started to use the big number factorial method to solve this problem. The result times out and the O (n2) algorithm cannot afford to hurt.
First, click the timeout code.
1 #include<cstdio> 2 #include<cstring> 3 #include<stdlib.h> 4 #include<algorithm> 5 using namespace std; 6 int main() 7 { 8 int kase,num[3000],i,j; 9 scanf("%d",&kase);10 while(kase--)11 {12 int n;13 scanf("%d",&n);14 memset(num,0,sizeof(num));15 num[0]=1;16 for(int i=2;i<=n;i++)17 {18 int c=0;19 for(int j=0;j<3000;j++)20 {21 num[j]=num[j]*i+c;22 c=num[j]/10;23 num[j]=num[j]%10;24 }25 }26 for(i=2999;i>=0;i--)27 if(num[i])28 break;29 printf("%d\n",i+1);30 }31 return 0;32 }
View code
Later, I thought that even if I didn't time out, the factorial of 10 ^ 7 would not exist, so I had no idea at the moment.
Later, I went online to see how the gods did it.
If you want to calculate the number of digits of a num, you can use (INT) lg (double) num) + 1
LG (1*2*3... n) = lg1 + lg2 + lg3 +... LG n
Here, you can set ~ The number of digits of 10 ^ 7 is all stored in table.
1 #include<cstdio> 2 #include<cmath> 3 #include<cstring> 4 #include<stdlib.h> 5 using namespace std; 6 int a[10000005]; 7 int main() 8 { 9 a[1]=1;10 double sum=0;11 for(int i=2;i<=10000000;i++)12 {13 sum+=log10((double)i);14 a[i]=sum+1;15 }16 int kase,n;17 scanf("%d",&kase);18 while(kase--)19 {20 scanf("%d",&n);21 printf("%d\n",a[n]);22 }23 return 0;24 }
View code
Of course, another way is to use the sterling number.
Formula:
Find the factorial and then use the same method to obtain the number of digits and obtain lg (N !) Then rounded up.
1 #include<cstdio> 2 #include<cmath> 3 #include<cstring> 4 #include<stdlib.h> 5 const double PI=3.141592654; 6 const double e=2.718281828; 7 using namespace std; 8 int main() 9 {10 int kase,n;11 double sum;12 scanf("%d",&kase);13 while(kase--)14 {15 scanf("%d",&n);16 sum=log10(2*PI*n)/2+n*log10(n/e);17 printf("%d\n",(int)sum+1);18 }19 return 0;20 }
View code