字符串解决大数阶乘

52 阅读1分钟

大数阶乘

​ 通常而言,我们一般只会算到20以内的阶乘,很少算到20以外的阶乘,因为后面的数比较大了,作者记得某年考研408真题就有考到过这种类似的题目。

一、20以内的阶乘

#include<iostream>

using namespace std;

int main(){
    int n;
    cin>>n;
    long result=1;
    for(int i=1;i<=n;i++){
        result*=i;
    }
    cout<<result;
    return 0;
}

如果超过20,计算阶乘就比较麻烦了,这个时候就需要用到大数阶乘才可以进行计算。

二、大数阶乘

大数阶乘问题,但是题目做了简化,限制n(1<=n<=20),所以普通解法就能通过。但是,如果不对n做限制呢?那就是典型的大数问题了,字符串是解决大数问题的有效手段,可能不是最简单的,但是是万能的。对这个题来说,只要实现了字符串的乘法,不管多大的n,都能实现阶乘的运算。例如a = “123”,b = “56”,a * b = “123” * “6” + “123” * “50”,而"123" * “50” = “123” * “5” + “0”. 这样就得到了两个大数相乘的结果。因此,要实现字符串相乘运算,首先要实现字符串和单个字符的相乘运算(其实是为了简化多位数乘法),然后要实现字符串的相加运算。这个思路实现如下:

#include <iostream>
#include <string>
using namespace std;

string add(const string a, const string b){
    string res;
    int i = a.size() - 1;
    int j = b.size() - 1;
    int extra = 0;
    while (i >= 0 && j >= 0){
        res = to_string((a[i] - '0' + b[j] - '0' + extra) % 10) + res;
        extra = (a[i] - '0' + b[j] - '0' + extra) / 10;
        i--;
        j--;
    }
    while (i >= 0){
        res = to_string((a[i] - '0' + extra) % 10) + res;
        extra = (a[i] - '0' + extra) / 10;
        i--;
    }
    while (j >= 0){
        res = to_string((b[j] - '0' + extra) % 10) + res;
        extra = (b[j] - '0' + extra) / 10;
        j--;
    }
    if (extra != 0)
        res = to_string(extra) + res;
    return res;
}

string _mul(const string a, const char b){
    string res;
    int extra = 0;
    int i = a.size() - 1;
    while (i >= 0){
        res = to_string(((a[i] - '0') * (b - '0') + extra) % 10) + res;
        extra = ((a[i] - '0') * (b - '0') + extra) / 10;
        i--;
    }
    if (extra != 0)
        res = to_string(extra) + res;
    return res;
}

string multiply(const string a, const string b){
    string res;
    for (int i = b.size() - 1; i >= 0; i--){
        string temp = _mul(a, b[i]);
        for (int j = 0; j < (int)b.length() - 1 - i; j++)
            temp = temp + "0";
        res = add(res, temp);
    }
    return res;
}

string factorial(int n){
    string res = "1";
    for (int i = 2; i <= n;i++){
        res = multiply(res, to_string(i));
    }
    return res;
}

int main(){
    int n;
    while (cin >> n){
        string res = factorial(n);
        cout << res << endl;
    }
    return 0;
}

分享一种大数阶乘的方法,大家可以粘在本地IDE上玩,亲测7700以下不熄火