大整数乘法 c++实现

17 篇文章 0 订阅
16 篇文章 0 订阅

 算法竞赛入门经典 这本书并没有对大数乘法实现,所以自己补充了一下,乘法的实现很简单,就是再其数据结构基础上把每宽为8位的十进制数看成多项式的系数,vector的下标看成多项式的指数,然后再对应相乘相加就可以了,注意系数超过8位 将超八位的补分进位。

我这里是朴素模拟相乘。但是不是用的网上普遍的char表示1位数字(用1B去实现0~9实在有点浪费), 而是借用4B的int 实现0~10e8-1的存储,减少了不必要的复杂度

实际上 这样优化朴素算法能通过很多需要FFT实现的OJ题. 

#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
using namespace std;
typedef long long LL;
struct BigInteger{
    static const int BASE = 100000000;
    static const int WIDTH = 8;
    vector<int> s;

    BigInteger operator = (const string& str){
        s.clear();
        int x, len=(str.length()-1)/WIDTH+1;
        for(int i=0;i<len;i++){
            int r=str.length()-i*WIDTH;
            int l=max(0,r-WIDTH);
            sscanf(str.substr(l,r-l).c_str(),"%d",&x);
            s.push_back(x);
        }
        return *this;
    }

    BigInteger operator * (const BigInteger& b){
        BigInteger c;
        int lena=this->s.size(),lenb=b.s.size(),lenc=lena+lenb-1;
        LL *buf =new LL[lenc+1];
        for(int i=0;i<lenc+1;i++)buf[i]=0;
        for(int i=0;i<lena;i++)
            for(int j=0;j<lenb;j++){
                buf[i+j]+=(this->s[i])*((LL)b.s[j]);
                buf[i+j+1]+=buf[i+j]/BASE;
                buf[i+j]=buf[i+j]%BASE;
            }
        for(int i=0;i<lenc;i++)c.s.push_back(buf[i]);
        if(buf[lenc])c.s.push_back(buf[lenc]);
        return c;
    }

    BigInteger operator * (const int& x){
        char c[128];
        sprintf(c,"%d",x);
        string str(c);
        BigInteger res;
        res=str;
        return *this*res;
    }
};

ostream& operator<<(ostream& out,const BigInteger& b){
    int len=b.s.size();
    out<<b.s[len-1];
    for(int i=len-2;i>=0;i--){
        int buf=b.s[i],h=8;
        while(buf>0){buf/=10;h--;}
        for(int j=0;j<h;j++)out<<0;
        if(b.s[i])out<<b.s[i];
    }
    return out;
}

int main()
{
    int n;BigInteger b;
    b="1000000000000";
    cout<< b<<endl;
    cout<< (b*b)*4*b*b <<endl;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值