阶乘的精确值

输入不超过1000的正整数n,输出n! = 1*2*3*4*....*n的结果。

样例输入:

30

样例输出:

265252859812191058636308480000000

 

解题思路:

如果我们采用一般的递归方法去做,那么结果一定会溢出。

所以这里我们采用f[3000]数组去存取,让f[0]保存结果的个位,f[1]是十位,f[2]是百位.........

这里我们为什么要逆序表示呢?因为如果我们按照高位到低位,一旦产生进位,那么就太麻烦了,

这里我们要解释下为什么f数组的容量要3000,因为1000!约等于4*10^2567。最后我们去掉前导的0即可。

//
//  main.cpp
//  c++prime
//
//  Created by SJCHEN on 2019/1/19.
//  Copyright © 2019 SJCHEN. All rights reserved.
//

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn = 3000;
int f[maxn];

int main()
{
    int i, j, n;
    cin >> n;
    memset(f,0,sizeof(f));
    f[0] = 1;
    for (i = 2; i <= n; i++) {
        int c = 0;
        for (j = 0; j < maxn; j++){
            int s = f[j]*i + c;
            f[j] = s % 10;
            c = s/10;
        }
    }
    for(j = maxn-1; j >= 0; j--) if (f[j]) break;//忽略前导的0
    for (i = j; i >= 0; i--) cout << f[i];
    cout << endl;
    return 0;
}

 

posted @ 2019-03-23 15:50  codeSJCHEN  阅读(247)  评论(0编辑  收藏  举报