[51nod1058]求N!的长度

法1:stirling公式近似

$n! \approx \sqrt {2\pi n} {(\frac{n}{e})^n}$

(如果怕n不够大下式不成立,可以当数小于10000时用for求阶层)

也可以用log10函数,不过直接使用log,e没有误差,一定注意longlong;

复杂度$O(1)$

 1 #include<bits/stdc++.h>
 2 #define PI  acos(-1.0)
 3 using namespace std;
 4 typedef long long ll;
 5 int main(){
 6     int n,t;
 7     cin>>t;
 8     double ans;
 9     while(t--){
10         cin>>n;
11         ans=(0.5*log(2*PI*n)+n*log(n)-n)/log(10);
12         cout<<(ll)ans+1<<endl;
13     }
14     return 0;
15 }

法二:

直接for+log10循环求,复杂度$O(n)$

 1 #include<bits/stdc++.h>
 2 #define PI  acos(-1.0)
 3 using namespace std;
 4 typedef long long ll;
 5 int main(){
 6     int n;
 7     cin>>n;
 8     double ans=1.0;//对10取对数之后需要+1 
 9     for(int i=1;i<=n;i++){
10         ans+=log10(i);
11     }
12     cout<<(int)ans<<endl;
13     return 0;
14 }

 

posted @ 2017-05-27 01:35  Elpsywk  阅读(211)  评论(0编辑  收藏  举报