P1009 [NOIP1998 普及组] 阶乘之和

题目传送门

//P1009.cpp

#include <bits/stdc++.h>

using namespace std;
//本题有坑,使用长整也过不了洛谷的用例,因为它的用例是22,需要高精度,也就是乘法高精度+加法高精度
typedef long long LL;
int n;
LL res;

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        LL f = 1;
        for (int j = 1; j <= i; j++)
            f *= j;
        res += f;
    }
    cout << res << endl;
    return 0;
}

//P1009_2.cpp

#include <bits/stdc++.h>

using namespace std;
typedef long long LL;
int n;
LL res;

int main() {
    cin >> n;
    LL f = 1;
    for (int i = 1; i <= n; i++) {
        f *= i;
        res += f;
    }
    cout << res << endl;
    return 0;
}

//P1009_3.cpp

#include <bits/stdc++.h>

using namespace std;
int n;

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

vector<int> mul(vector<int> &A, int b) {
    vector<int> C;
    int t = 0;
    for (int i = 0; i < A.size() || t; i++) {
        if (i < A.size()) t += A[i] * b;
        C.push_back(t % 10);
        t /= 10;
    }
    while (C.size() > 1 && C.back() == 0) C.pop_back();
    return C;
}

int main() {
    cin >> n;
    vector<int> A, S;
    //初始化
    A.push_back(1);
    S.push_back(1);
    for (int i = 2; i <= n; i++) {
        A = mul(A, i);
        S = add(A, S);
    }
    for (int i = S.size() - 1; i >= 0; i--)printf("%d", S[i]);
    return 0;
}

//P1009_Prepare.cpp

#include <bits/stdc++.h>

using namespace std;
typedef long long LL;

//母题
//求n阶乘
LL f(int n) {
    LL s = 1;
    for (int i = 1; i <= n; i++) s *= i;
    return s;
}

int main() {
    //INT_MAX
    //2147483647
    // s=1!+2!+3!+...+n!
    // 3!=3*2*1
    // 4!=4*3*2*1 四步
    // 4!=4*3!    一步,3!我知道

    //20!=20*19*18*....*1
    LL s = 0;
    for (int i = 1; i <= 20; i++) s += f(i);
    cout << s << endl;


    LL t = 1;
    s = 0;
    for (int i = 1; i <= 20; i++) t = t * i, s += t;
    cout << s << endl;
    return 0;
}
posted @   糖豆爸爸  阅读(1090)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2014-11-21 mysql查看每张表的空间使用情况
Live2D
点击右上角即可分享
微信分享提示