N!

本文提供了一种解决大数阶乘问题的算法实现方案,针对传统整型数据溢出的情况,采用数组来存储大数并实现了阶乘运算。通过具体代码示例展示了如何处理从1到给定整数的大数阶乘计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来自杭电:http://acm.hdu.edu.cn/showproblem.php?pid=1042
Problem Description

Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!

Input

One N in one line, process to the end of file.

Output

For each N, output N! in one line.

Sample Input

1
2
3

Sample Output

1
2
6

代码:

#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

int main()
{
    int n;
    int i;
    int j;
    int digit;  //总位数
    int a[40000];
    int carry;  //进位
    int temp;
    int len;
    //ofstream cout("out.txt");
    while(cin >> n){
        memset(a,0,sizeof(a));
        temp = 0;
        digit = 1;
        a[0] = 1;
        for(i = 2;i <= n;i++){
            carry = 0;
            for(j = 1;j <= digit;j++){
                temp = a[j-1] * i + carry;
                a[j-1] = temp % 10;
                carry  = temp /10;
            }
            while(carry){
                a[++digit - 1] = carry % 10;
                carry /= 10;
            }
        }
        for(i = digit-1;i >= 0;i--)
            cout << a[i];
        cout << endl;

    }
    return 0;
}

总结:还是大数问题,一般情况下12的阶乘就已经溢出,因此考虑用数组存储,关于大数阶乘,有很多很多好的算法,此处只是个很简单的,仅仅比递归想的多了点,奉上大神之作http://blog.youkuaiyun.com/whdugh/article/details/9364245

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值