51nod 1130 N的階乘的長度(階乘近似公式--斯特林公式)



大致題意:

求n!有多少位,n<= 1e9 ,1000組數據


大致思路:

顯然是企圖求 lg(n!)+1 向下取整

顯然求lg(n!) 展開的複雜度是On的

但是,他是求多少位,有n!的近似公式斯特林公式(Stirling's approximation)

n! \sim \sqrt{2 \pi n}\left(\frac{n}{e}\right)^n.

維基百科:https://en.wikipedia.org/wiki/Stirling%27s_approximation


顯然對於求對數函數來說精確度在n比較大的情況下必然滿足。






//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <ctime>
#include <bitset>
#include <algorithm>
#define SZ(x) ((int)(x).size())
#define ALL(v) (v).begin(), (v).end()
#define foreach(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); ++ i)
#define reveach(i, v) for (__typeof((v).rbegin()) i = (v).rbegin(); i != (v).rend(); ++ i)
#define REP(i,n) for ( int i=1; i<=int(n); i++ )
#define rep(i,n) for ( int i=0; i< int(n); i++ )
using namespace std;
typedef long long ll;
#define X first
#define Y second
#define PB push_back
#define MP make_pair
typedef pair<int,int> pii;

template <class T>
inline bool RD(T &ret) {
    char c; int sgn;
    if (c = getchar(), c == EOF) return 0;
    while (c != '-' && (c<'0' || c>'9')) c = getchar();
    sgn = (c == '-') ? -1 : 1;
    ret = (c == '-') ? 0 : (c - '0');
    while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');
    ret *= sgn;
    return 1;
}
template <class T>
inline void PT(T x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) PT(x / 10);
    putchar(x % 10 + '0');
}

const double pi = acos(-1);

int main(){

        int T;
        RD(T);
        while( T--){
                ll n;
                RD(n);
                ll ans = log10(2*pi*n)/2 + n*(log10(n/exp(1.0)));
                PT(ans+1); puts("");
        }
}


Input
第1行:一個數T,表示後面用作輸入測試的數的數量。(1 <= T <= 1000)
第2 - T + 1行:每行1個數N。(1 <= N <= 10^9)
Output
共T行,輸出對應的階乘的長度。
Input示例
3
4
5
6
Output示例
2
3
3


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章