c++的大数阶乘算法

#include<iostream>
using namespace std;
#include<string>
const int MAX = 3000;
int a[MAX];
int fac(int n) {
    memset(a, 0, sizeof(a));//初始化0;下面的a[j] = a[j] * i + c计算过程中会用到a[j]=0
    int top = 0;//最高位
    a[0] = 1;
    int c = 0;//用于判断是否进位,也就是j是否+1。
    for (int i = 2; i <= n; i++) {//i为用来阶乘的数字,就是2~n之间的数字
        for (int j = 0; j <= top; j++) {  //j循环用来将计算出来的结果按位分割并存储到数组中
            a[j] = a[j] * i + c;
            c = a[j] / 10;//c就是下一次再次进入j循环时的a[j]初始值,结合下面的判断语句
                          //如果这里的c<10,top最高位就没必要再加了,如果c>10,则继续分割,知道c<10为止
            if (j == top && c >= 1) {
                top++;
            }
            a[j] = a[j] % 10;//取余得到第j位上该放置的数字
        }
    }
    for (int i = top; i >= 0; --i) {
        cout << a[i];
    }
    return 0;
}
int main() {
    int n;
    cout << "请输入一个数字n" << endl;
    cin >> n;
    fac(n);
    
}
原文地址:https://www.cnblogs.com/nanfengnan/p/15771882.html