大数乘法(非FFT)

注意点:
1.两个数相乘的时候,要用long long 防止溢出
2.最后输出的时候,位数不够前面补0,用的是 %.9d 反正阔以这样用(っ•̀ω•́)っ✎⁾⁾ 我爱学习

#include"iostream"
#include"algorithm"
#include"string.h"
using namespace std;
const int maxn=2e5+5;
const int MOD=1e9;
typedef long long  LL;
struct Big
{
    int n;
    int a[maxn];
};
Big c2n(char *s)
{
    int len=strlen(s);
    Big t;
    t.n=len/9;
    memset(t.a,0,sizeof(t.a));
    int tp;
    for(int i=0,j=len-1;i<len;i++,j--)
    {
        if(i%9==0)tp=1;
        t.a[i/9]+=(s[j]-'0')*tp;
        tp*=10;
    };
    return t;
}
Big operator*(Big a,Big b)
{
    Big res;
    res.n=a.n+b.n+2;
    memset(res.a,0,sizeof(res));
    for(int i=0;i<=a.n;i++)
    for(int j=0;j<=b.n;j++)
    {
        LL tp=(LL)a.a[i]*b.a[j];
        tp+=res.a[i+j];
        res.a[i+j+1]+=tp/MOD;
        res.a[i+j]=tp%MOD;
    }

    while(res.a[res.n]==0)res.n--;

    return res;
}
void print(Big res)
{
    cout<<res.a[res.n];
    for(int i=res.n-1;i>=0;i--)printf("%.9d",res.a[i]); 
    cout<<"\n";
}
int main()
{
    char a[maxn],b[maxn];
    while(cin>>a>>b)
    {
        Big aa=c2n(a),bb=c2n(b);
        Big res=aa*bb;
        print(res);
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务