大数n!

通常解决大数运算数据超出范围,溢出的问题。一般采用数组去模拟。求算n!可以看成是每次两个整数相乘的过程,因此可以模拟成大数相乘的过程。只是需要增加一些变量去存储中间的进位和当前位的数值。

#include <iostream>
using namespace std;
#define MAX_WEI 100000
int result[MAX_WEI];
int wei_location;
int up;
int main()
{
    int i,n;
    int j;
    while(scanf("%d",&n)!=EOF)
    {
        memset(result,sizeof(result));
        result[1] =1;
        wei_location=1; //当前结果的位数,便于相乘和最后输出
        up =0;
        if(n==0 || n==1)
        {
            printf("1\n");
            continue;
        }
        for(i=2;i<=n;i++) //n!中的每个数
        {
            for(j =1,up =0;j<=wei_location;j++)  //模拟乘法步骤:每一位与当前数相乘
            {
                result[j] = result[j] *i + up; //当前数+前面的进位数
                up = result[j]/10; 
                result[j] =result[j]%10;  //每个数存一位
            }
            while(up > 0)
            {
                result[j++] += up%10;  //注意跳出来是j是多一的
                up= up/10;
            }
            wei_location= j -1;//注意跳出来是j是多一的
        }
        for(i = wei_location;i>=1;i--)
            (i!=1)? printf("%d",result[i]) : printf("%d\n",result[i]);
    }
    return 0;
}

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...