阶乘位数

昨天校赛模拟赛考了个题,不会这个知识点还真做不出来。。。。

 

 

1. O(n)解法 , n 为数的大小:

log10(n!)=log10(1*2*3…*n)=log10(1)+log10(2)+…+log10(n)+1

即对log10(n!)的值取整加1就是n!的位数。

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 int main(){
 5     int n;
 6     double d=0;
 7     cin>>n;
 8     for(int i=1;i<=n;i++)    {
 9         d+=log10(double(i));
10     }
11     cout<<"n阶乘的位数位: "<<(int)(d+1)<<endl;
12     return 0;
13 }

 

效率太慢,肯定超时。

 

2. O(1)解法,近似计算的方法,斯特林公式。n!近似等于sqrt(2*pi*n) * (n/e)^n

#include <iostream>
#include <cmath>
using namespace std;
int main(){
    int t;
    cin >> t;
    while (t--) {
        int n;
        double d = 0;
        cin >> n;
        if( n == 1 || n == 0){
            d = 1;
        }else{
            d = log10(double(2 * M_PI * n))/2 + n * log10(double( n / M_E));
        }
        cout << (int)ceil(d) << endl;
    }
    return 0;
}
posted @ 2020-03-29 09:09  popozyl  阅读(276)  评论(0编辑  收藏  举报