LETTers比赛第四场-N!的最高位

N!的最高位

该题如果直接用上述方法必然会超时,因为只要最高位,精确的方法可以是x=(int)(10^( log10(N!)-(int)log10(N!))),但由于n可能很大,这样都会超时,这里用到一个公式,Stirling公式,在n较小时直接给出,在较大时用Sterling公式算出n!近似值,再求的最高位。

#include<iostream>
#include<math.h>
using namespace std;
const double PI = 3.14159265358979323846;
const double E = 2.71828182845904523536;
const int m[9] = {1,1,2,6,2,1,7,5,4};
int main(void)
{
    int n;
    double k;
    while(cin >> n)
    {
        if(n<=8)
        {
            cout << m[n] << endl;
            continue;
        }
        k = log10(2*PI*n)/2 + n*log10(n/E);
        cout << int(pow(10, k-int(k))) << endl;
    }
    return 0;
}
posted @ 2012-04-18 22:23  LETTers  阅读(242)  评论(0编辑  收藏  举报