大佬帮帮我

P1009 [NOIP1998 普及组] 阶乘之和

are_you_clever @ 2023-08-06 19:07:17

循环1000万就超时了,怎么办啊!


by lzyzs @ 2023-08-06 19:21:46

上码seeeeeee


by kunkun123456 @ 2023-08-06 20:52:30

#include<bits/stdc++.h>
using namespace std;
int n;
vector<int> jia(vector<int>a, vector<int>b )
{
    vector<int> ans;
    if(a.size()<b.size()) swap(a,b);
    int t=0;
    for(int i=0;i<a.size();i++)
    {
        t+=a[i];
        if(i<b.size()) t+=b[i];
        ans.push_back(t%10);
        if(t>=10) t=1;
        else t=0;
    }
    if(t) ans.push_back(t);
    return ans;
}
vector<int> mul(vector<int> a,int b)
{
    vector<int> res;
    for (int i = 0; i < a.size(); i++)
        a[i] *= b;
    int t = 0;
    for (int i = 0; i < a.size(); i++) 
    {
        t += a[i];
        res.push_back(t%10);
        t /= 10;
    }
    while (t) res.push_back(t%10), t /= 10; 
    while (res.size() > 1 && res.back() == 0) res.pop_back();
    return res;
}
vector<int> func(int a)
{
    vector<int> ans;
    ans.push_back(1);
    for(int i=1;i<=a;i++)
    {
        ans=mul(ans,i);
    }
    return ans;
}
int main()  
{
    cin>>n;
    vector<int> ans;
    ans.push_back(0);
    for(int i=1;i<=n;i++)
    {
        ans=jia(ans,func(i));
    }
    for(int i=ans.size()-1;i>=0;i--)
    {
        cout<<ans[i];
    }
}

by kunkun123456 @ 2023-08-06 20:53:03

记得点赞


by _ant_ant @ 2023-08-09 12:29:09

@kunkun123456

这样更好:

#include<bits/stdc++.h>
using namespace std;
struct Bigint{
    int len,a[101]={0};
    Bigint(int x=0){
        for(len=1;x;len++)
            a[len]=x%10,x/=10;
        len--;
    }
    int &operator[](int i){
        return a[i];
    }
    void flatten(int L){
        len=L;
        for(int i=1;i<=len;i++)
            a[i+1]+=a[i]/10,a[i]%=10;
        for(;!a[len];)
            len--;
    }
    void print(){
        for(int i=max(len,1);i;i--)
            printf("%d",a[i]);
    }
};
Bigint operator+(Bigint a,Bigint b){
    Bigint c;
    int len=max(a.len,b.len);
    for(int i=1;i<=len;i++)
        c[i]+=a[i]+b[i];
    c.flatten(len+1);
    return c;
}
Bigint operator*(Bigint a,int b){
    Bigint c;
    int len=a.len;
    for(int i=1;i<=len;i++)
        c[i]=a[i]*b;
    c.flatten(len+11);
    return c;
}
int n;
Bigint ans(0),fac(1);
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        fac=fac*i;
        ans=ans+fac;
    }
    ans.print();
    return 0;
}

by are_you_clever @ 2023-10-20 21:34:57

@_ant_ant 我要精神大爆发了


|