大数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,0,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;
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值