【题目】阶乘之和

原题链接

代码展示

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

vector<int> add(vector<int> &A,vector<int> &B)
{
	vector<int> C;
	int t=0;
	for(int i=0;i<A.size() || i<B.size();i++)
	{
		if(i<A.size()) t+=A[i];
		if(i<B.size()) t+=B[i];
		C.push_back(t%10);
		t/=10;
	} 
	if(t) C.push_back(1);
	return C;
}

void calculateFactorial(int n, vector<int> &result) {
    result.push_back(1);

    for (int i = 2; i <= n; ++i) {
        int carry = 0;
        for (size_t j = 0; j < result.size(); ++j) {
            int product = result[j] * i + carry;
            result[j] = product % 10;
            carry = product / 10;
        }
        while (carry > 0) {
            result.push_back(carry % 10);
            carry /= 10;
        }
    }
}

int main() {
	int n;
	cin >> n;
	vector<int> sum;
	for(int i=1;i<=n;i++){
	vector<int> factorial;
    calculateFactorial(i, factorial);
	sum = add(sum, factorial);
	}
    for(int i=sum.size()-1;i>=0;i--){
		cout << sum[i];
	}
	return 0;
} 

第二段函数calculateFactorial是求大数阶乘。这一段实际是将上一篇文章的高精度计算融合起来得出的。

后续优化(统一,简单易懂,简洁)

#include <iostream>
#include <vector>
using namespace std;
vector<int> add(vector<int> a, vector<int> b){
    vector<int> c(a.size()+b.size(),0);
    int carry = 0;
    for(int i = 0; i<a.size() || i<b.size(); i++){
        if(i<a.size()) carry += a[i];
        if(i<b.size()) carry += b[i];
        c[i] = carry%10;
        carry /= 10;
    }
    while(carry){
        c.push_back(carry%10);
        carry /= 10;
    }
    return c;
}

vector<int> facterial(int n){
    vector<int> original(1,1);
    for(int i = 1; i <= n; i++){
        int carry = 0;
        for(int j = 0; j < original.size(); j++){
            int product = original[j]*i + carry;
            original[j] = product%10;
            carry = product/10;
        }
        while(carry){
            original.push_back(carry%10);
            carry /= 10;
        }
    }
    return original;
}

int main(){
    vector<int> sum;
    const int MAX = 20;
    for(int i = 1; i <= MAX; i++){
        sum =add(sum,facterial(i));
    }
    while(sum.back() == 0 && sum.size() > 1) sum.pop_back();
    for(int i = sum.size()-1; i>=0; i--){
        cout<<sum[i];
    }
    return 0;
} 
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇