hdu 1042 大数阶乘

原文链接: hdu 1042 大数阶乘

上一篇: HDU 5832 / HDU 1212 A water problem (大数取模)

下一篇: hdu3123 大数阶乘求和取模

高精度问题:大整数乘法的应用

其核心思想就是把计算结果每一位上的数字保存到一个数组成员中,例如:
把124保存至数组中,保存结果应该是result[0] =4;result[1] =2;result[2] =1
把整个数组看成一个数字,这个数字和一个数相乘的时候,需要每一位都和这个乘数进行相乘运算还需要把前一位的进位加上。

写法如下:int 结果 = result[x] * 乘数 + 进位;
每一位的计算结果有了,把这个结果的个位数拿出来放到这个数组元素上:result[x] = 结果%10;
接下来的工作就是计算出进位:进位 = 结果 / 10;
这样一位一位的把整个数组计算一遍,最后可能还有进位,用同样的方法,把进位的数值拆成单个数字,放到相应的数组元素中。最后从后往前输出结果。

使用十进制

193707_EBtM_2856757.png

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>

#define LL long long
int const MAX = 50000;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;
//计算n!

int ans[MAX], n, len, t;
int main(){
    while (scanf("%d", &n) == 1){
        memset(ans, 0, sizeof(ans));
        ans[0] = 1;
        len = 1;
        for (int i = 2; i <= n; i++){
            t = 0;
            for (int j = 0; j < len; j++){
                t = i * ans[j] + t;
                ans[j] = t % 10;
                t /= 10;

            }
            while (t){
                ans[len++] = t % 10;
                t /= 10;
            }

        }

        for (int i = len - 1; i >= 0; i--)
            printf("%d", ans[i]);
        printf("\n");

    }
    return 0;
}

使用万进制,注意输出格式问题

194734_tqLb_2856757.png

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>

#define LL long long
int const MAX = 1e6 + 1;
int const INF = 1 << 30;
double const EPS = 0.00000001;
using namespace std;

//使用万进制
int a[10000], t, len, n, mod = 10000;
int main(){
    while (scanf("%d", &n) == 1){
        memset(a, 0, sizeof(a));
        a[0] = 1;
        len = 1;
        for (int i = 2; i <= n; i++){
            t = 0;
            for (int j = 0; j < len; j++){
                t = i * a[j] + t;
                a[j] = t % mod;
                t /= mod;
            }
            while (t){
                a[len++] = t % mod;
                t /= mod;
            }
        }

        for (int i = len - 1; i >= 0; i--){
            if (i == len - 1) printf("%d", a[i]);
            else {
                if (a[i] < 10)
                    printf("000%d", a[i]);
                else if (a[i] < 100)
                    printf("00%d", a[i]);
                else if (a[i] < 1000)
                    printf("0%d", a[i]);
                else
                    printf("%d", a[i]);
            }
        }
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值