CSP历年复赛题-P1009 [NOIP1998 普及组] 阶乘之和

原题链接:https://www.luogu.com.cn/problem/P1009

题意解读:

  利用高精度计算阶乘之和,需要用到高精度乘法(高精度乘低精度)、高精度加法。

  首先,思考不利用高精度如何解题,直观方法就是遍历i从1到n,每次乘i得到i的阶乘,然后累加到结果,代码如下:

#include <bits/stdc++.h>
using namespace std;

int res; //结果
int fac = 1; //阶乘
int n;

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        fac *= i;
        res += fac;
    }
    cout << res;

    return 0;
}

  然后,将其中需要转变为高精度的地方进行替换,整数变量要替换为vector数组,乘法、加法操作替换为高精度函数操作,可得:

#include <bits/stdc++.h>
using namespace std;

vector<int> res; //结果
vector<int> fac(1, 1); //阶乘
int n;

void mul(int i)
{

}

void add()
{

}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        mul(i);  //将fac乘以i
        add(); //将fac加到res上
    }
    for(int i = res.size() - 1; i >= 0; i--) cout << res[i];

    return 0;
}

  最后,实现mul、add函数进行高精度乘法、加法操作。

100分代码:

#include <bits/stdc++.h>
using namespace std;

vector<int> res; //结果
vector<int> fac(1, 1); //阶乘
int n;

//mul函数实现fac = fac * b
void mul(int b)
{
    vector<int> result;
    int t = 0;
    for(int i = 0; i < fac.size(); i++)
    {
        t += fac[i] * b;
        result.push_back(t % 10);
        t /= 10;
    }
    while(t)
    {
        result.push_back(t % 10);
        t /= 10;
    }
    fac = result;
}

//add函数实现res = res + fac
void add()
{
    vector<int> result;
    int t = 0;
    int len = max(res.size(), fac.size());
    for(int i = 0; i < len; i++)
    {
        if(i < res.size()) t += res[i];
        if(i < fac.size()) t += fac[i];
        result.push_back(t % 10);
        t /= 10;
    }
    if(t) result.push_back(t);
    res = result;
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        mul(i);  //将fac乘以i
        add(); //将fac加到res上
    }
    for(int i = res.size() - 1; i >= 0; i--) cout << res[i];

    return 0;
}

 

posted @   五月江城  阅读(224)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示