1. 程式人生 > >poj 1423 打表/斯特林公式

poj 1423 打表/斯特林公式

分享圖片 namespace i++ png 調用 exp oid cout sin

技術分享圖片

對於n位數的計算,我們可以采用(int)log10(n) + 1的方法得到n的位數

第一種方法:

對於n!位數的計算,log10(n!) = log10(1) + log10(2) + ... + log10(n)

為防止直接暴力超時這部分運算可以打表等待主程序調用

#include<iostream>
#include<cmath>
using namespace std;

const int MAXN = 1e7;
int ans[MAXN +1];

void action(int m)//打表計算n!位數,存在ans數組中 
{
    double d = 0;
    
for(int i = 1;i<=m;i++) { d += log10(double(i));//累加log10(i) ans[i] = (int)d + 1;//向下取整並+1 } } int main() { int n,m; cin>>n; action(MAXN); while(n--) { cin>>m; cout<<ans[m]<<endl; } return 0; }

第二種方法:

對於n!的計算,也可以用斯特林公式:

技術分享圖片

然後直接計算(int)log10(n!) + 1

#include<iostream>
#include<cmath>
using namespace std;

double pi = acos((double)-1);

int main()
{
    int n,m;
    cin>>n;
    while(n--)
    {
        cin>>m;
        cout<<(int)(log10(sqrt(2 * m * pi) )+ m * log10(m / exp((double)1)))+ 1<<endl;
    }
}

poj 1423 打表/斯特林公式