【洛谷】大数阶乘

题目链接就不放了。

之前在打比赛的时候,一直大数都是抄的板子。自己写了一下发现还可以吧。最主要的就是要注意数组的大小问题。因为加法和乘法的结果的长度是不一样的。

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 500;
vector<int> a(maxn), b(maxn);
vector<int> add(vector<int> a, vector<int> b)
{
    vector<int> ans(maxn);
    int carry = 0;
    for(int i=0;i<maxn;i++)
    {
        ans[i] = a[i] + b[i] + carry;
        carry = ans[i]/10;
        ans[i] %= 10;
    }
    return ans;
}
vector<int> mul(vector<int> a, vector<int> b)
{
    vector<int> ans(maxn);
    for(int i=0;i<maxn/2;i++) //b
    {
        int carry = 0;
        for(int j=0;j<maxn/2;j++) //a
        {
            ans[i+j] += a[j] * b[i] + carry;
            carry = ans[i+j] / 10;
            ans[i+j] %= 10;
        }
    }
    return ans;
}
vector<int> int2vec(int x)
{
    vector<int> ans(maxn);
    int cnt = 0;
    while(x)
    {
        ans[cnt++] = x%10;
        x /= 10;
    }
    return ans;
}
void print(vector<int> a)
{
    reverse(a.rbegin(),a.rend());
    bool found = false;
    for(auto val:a)
    {
        if(val!=0) found = true;
        if(found) printf("%d",val);
    }
    printf("\n");
}
int main()
{
    int x;
    scanf("%d",&x);
    vector<int> ans(maxn),tmp,tmp2;
    for(int i=1;i<=x;i++)
    {
        tmp = int2vec(1);
        for(int j=1;j<=i;j++)
        {
            tmp2 = int2vec(j);
            tmp = mul(tmp, tmp2);
        }
        ans = add(ans, tmp);
    }
    print(ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值