C++ to achieve large integer multiplication

  • 2020-06-19 11:18:31
  • OfStack

Introduction to this book is not for large classic algorithm competition multiplication implementation, so their added 1, the realization of the multiplication is very simple, is based on the data structure to wide for 8-bit decimal number as a polynomial coefficients, the subscript vector as polynomial index, and then corresponding multiplication addition, note coefficient of more than eight super 8 points and carry.

I'm doing Cartesian multiplication here. Generally speaking, it is enough.

But there are many more efficient polynomial multiplication algorithms.


#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;
}

Related articles: