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.
2 10 20
7 19
给你一个数n,要你求他的阶乘有几位数字组成;一看到这题就条件反射的觉得要用大数才能解决,结果折腾了老久,竟然不对。然后去看大神的代码,要不是最近天气热,没吃啥东西,差点一口老血喷将出来;尼玛我敲了好长的代码,他给我就简简单单的几行,就用了一个函数log10()来自变量的位数,而这题给的是阶乘,比如说log10(3!)=log(1*2*3)=log(1)+log(2)+log(3);一个函数,一个for循环,丫的就解决的干干精简。这就是和大神的差距啊。不过也算赚到了。利用log10()的特点求位数 。
#include <iostream> #include <cstdio> #include <cmath> using namespace std; int a[100][100000]; int main() { int t;cin>>t; while(t--) { int n;cin>>n;double sum=0;//在这里sum由于要进行相加求和,只能是double,而在求单独一个 for(int i=1;i<=n;i++)//数的位数时可以用int来盛装 { sum+=log10(i); } cout<<(int)sum+1<<endl; } }
除此之外,这道题还可以用斯特林公式来求
//此题必须用公式才能AC,数据规模太大了 //Stirling公式: n! = ((2*pi*n)^(1/2))*((n/e)^n); 前提是n > 3 //由此可以导出lg(n!) = (lg(2*pi)+lg(n))/2 + n*(lg(n)-lg(e)); #include<iostream> #include<cmath> using namespace std; int main() { int test,n; long long int s; const long double c1 = 0.798179868358; //lg(2*pi) const long double c2 = 0.434294481903; //lg(e) long double c3; cin >> test; while(--test+1) { cin >> n; c3 = log10((double)n); s = 1; if(n > 3) { s = (c3 + c1)/2 + n * (c3 - c2) + 1; cout << s << endl; } else cout << 1 << endl; } return 0; }
据说这个公式可以解决和阶乘相关的一切问题,我表示太强了