前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >阶乘计算【 数组模拟阶乘 】

阶乘计算【 数组模拟阶乘 】

作者头像
Lokinli
发布2023-03-09 13:59:59
7380
发布2023-03-09 13:59:59
举报
文章被收录于专栏:以终为始

阶乘计算

Description

输入一个正整数n,输出n!的值。

其中n!=123…n。

算法描述

n!可能很大,而计算机能表示的整数范围有限,需要使用高精度计算的方法。使用一个数组A来表示一个大整数a,A[0]表示a的个位,A[1]表示a的十位,依次类推。

将a乘以一个整数k变为将数组A的每一个元素都乘以k,请注意处理相应的进位。

首先将a设为1,然后乘2,乘3,当乘到n时,即得到了n!的值。

Input

输入包含一个正整数n,n<=1000。

Output

输出n!的准确值。

Sample Input 1 

代码语言:javascript
复制
10

Sample Output 1

代码语言:javascript
复制
3628800

解析:模拟一遍即可。

代码语言:javascript
复制
#include <iostream>
#include <cstdio>
#include <cstring>
#include <bits/stdc++.h>
#include <queue>
#include <algorithm>
#include <map>
#include <cstdlib>
using namespace std;
#define inf 0x3f3f3f3f
int a[100000];
int main()
{
    int n,top,m,temp,tmp;
    scanf("%d", &n);
    top = 0;
    a[top++]=1;
    temp = 0;
    for(int i = 1; i <= n; i ++)
    {
        // 每一位相乘
        for(int j = 0; j < top; j ++)
        {
            temp = temp + a[j] * i;
            a[j] = temp % 10;
            temp = temp / 10;
        }
        // 如果数最高位有进位,进位
        while(temp){
            a[top ++] = temp % 10;
            temp /= 10;
        }

//        for(int i = top-1; i >=0 ; i --)printf("%d",a[i]);printf("\n");
    }
    for(int i = top - 1; i >= 0; i --)
    {
        printf("%d",a[i]);
    }
    printf("\n");
    return 0;
}

> 803 就爆了,没想到咋错。。。。

代码语言:javascript
复制
#include <iostream>
#include <cstdio>
#include <cstring>
#include <bits/stdc++.h>
#include <queue>
#include <algorithm>
#include <map>
#include <cstdlib>
using namespace std;
#define inf 0x3f3f3f3f
int a[100000];
int main()
{
    int n,top,m,temp,tmp;
    scanf("%d", &n);
    top = 0;
    a[top++]=1;
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 0; j < top; j ++)
        {
            temp = a[j] * i;
            if(j == 0)
            {
                a[j] = temp % 10;
                tmp = temp / 10; // tmp 为进位
            }
            else
            {
                temp = temp + tmp;
                a[j] = temp % 10;
                tmp = temp / 10;

            }
            if(j == top - 1)
            {
                if(temp/10>=1)a[top ++] = temp / 10;
                break;

            }

        }
//        for(int i = top-1; i >=0 ; i --)printf("%d",a[i]);printf("\n");
    }
    for(int i = top - 1; i >= 0; i --)
    {
        printf("%d",a[i]);
    }
    printf("\n");
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 阶乘计算
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档