大数阶乘(C/C++)

高精度的运算在Java中是很容易实现的,就像 a + b Problem 一样,因为Java提供了相应的类库和API;但是在 C/C++ 当中就没有那么现成的类和API来让你调用了。本着“自己动手,丰衣足食”的Coder精神,还是自己上吧。让我们一起看看如何使用 C/C++ 来进行大数的阶乘吧。

/*
 *From:《算法竞赛入门经典》――刘汝佳
 *Author:YQ_beyond
 *Date:2015.03.29
*/

/*
  C++当中高精度运算
*/

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

const int maxn = 3000;
int res[maxn];

int main()
{
    int i, j, n;
    while(1)
    {

        scanf("%d",&n);
        memset(res,0,sizeof(res));
        res[0] = 1;

        int cut = 1;
        for(i = 1 ; i <= n ; i++)
        {
            int cnt = 0;
            for(j = 0;j < cut; j++)
            {
                int s = res[j] * i + cnt;
                res[j] = s % 10;
                cnt = s / 10;
            }
            for(; cnt != 0; j++)
            {
                int s = res[j] * i + cnt;
                res[j] = s % 10;
                cnt = s / 10;
                cut ++;
            }
        }

        //for(j = maxn - 1; j >= 0; j--) if(res[j]) break;
        for(i = cut - 1; i >= 0; i--) printf("%d",res[i]);
        printf("\n");
    }
    return 0;
}
The quieter you become, the more you are able to hear.
原文地址:https://www.cnblogs.com/yqbeyond/p/4391991.html