加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

hdu 1042 大数阶乘

发布时间:2020-12-14 05:02:38 所属栏目:大数据 来源:网络整理
导读:高精度问题:大整数乘法的应用 其核心思想就是把计算结果每一位上的数字保存到一个数组成员中,例如: 把124保存至数组中,保存结果应该是result[0] =4;result[1] =2;result[2] =1 把整个数组看成一个数字,这个数字和一个数相乘的时候,需要每一位都和这

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

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

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

?

使用十进制

#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,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;
}

?

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

#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,mod = 10000;
int main(){
    while (scanf("%d",&n) == 1){
        memset(a,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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读