大数阶乘

来源:互联网 发布:网络配线架有什么用 编辑:程序博客网 时间:2024/06/13 05:01
#include <iostream>
#include<stdlib.h>
using namespace std;
int car(int a[], int pos) {
    int i, carry = 0;
    for (i = 0; i <= pos; i++) {
        a[i] += carry;
        if (a[i] <= 9) carry = 0;
        else if (a[i] > 9 && i < pos) {
            carry = a[i] / 10;
            a[i] = a[i] % 10;
        }
        else if (a[i] > 9 && i >= pos) {
            while (a[i] > 9) {
                carry = a[i] / 10;
                a[i] = a[i] % 10;
                i++;
                a[i] = carry;
            }
            return i;
        }
    }
    return pos;
}
int main() {
    int m,i,j,*a,intl,pos,fpo;
    double l=0;
    cin >> m;
    for (i = 1; i <= m; i++)                                   //计算结果的位数
        l += log10(i);
    intl = (int)l + 1;
    a = (int*)malloc((intl+1) * sizeof(int));
    for (i = 0; i <= l + 2; i++)
        a[i] = 0;                                      //初始化数组
    a[0] = 1;
    for (i = 2; i <= m; i++) {                                      //累乘的循环
        for (j = intl; j >=0; j--) {                                      //查找最高位
            if (a[j] != 0) {
                pos = j;
                break;
            }
        }
        for (j = 0; j <= pos; j++)
            a[j] *= i;
        fpo=car(a, pos);                                 //进位并记录新的最高位
    }
    for (i = fpo; i >= 0; i--)                           //输出
        cout << a[i];

    return 0;
}
原创粉丝点击