大数阶乘的总结笔记

大数阶乘的总结

    大数阶乘也是大数运算的一种,由于大数已经超过了一般数值类型所能表示的范围,所以要用大数运算的方法来解决,大数运算的核心思想就是用数组来存储。首先,输入所要运算的阶乘的数,然后对其进行运算,将其结果倒序存入数组当中,然后去除数组当中前面为0的元素,然后再逆序输出即可。代码如下:
#include <bits/stdc++.h>
using namespace std;
int A[10000] = {
    
    0};  //存结果,注意大的静态数组要定义在全局
int main()
{
    
    
    int n;
    cin >> n;   //输入需求的阶乘数

    A[0] = 1;
    for(int i = 1;i <= n;i++)
    {
    
    
        int carry = 0;            //进位
        for(int j = 0;j < 10000;j++)
        {
    
    
            A[j] = A[j] * i + carry;        //计算当前位的大小
            carry = A[j] / 10;             //算出有没有进位的数
            A[j] = A[j] % 10;        //进位后当前位的大小
        }
    }
    int last;
    for(int i = 10000 - 1;i >= 0;i--)    //去除前面的0
    {
    
    
        if (A[i] != 0)
        {
    
    
            last = i;
            break;
        }
    }
    for(int i = last; i >= 0;i--)
        cout << A[i];

    return 0;
}

Guess you like

Origin blog.csdn.net/m0_52780705/article/details/121323792
Recommended