溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++怎么實現(xiàn)大整數(shù)乘法

發(fā)布時間:2021-04-14 11:26:28 來源:億速云 閱讀:169 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關(guān)C++怎么實現(xiàn)大整數(shù)乘法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

算法競賽入門經(jīng)典 這本書并沒有對大數(shù)乘法實現(xiàn),所以自己補充了一下,乘法的實現(xiàn)很簡單,就是再其數(shù)據(jù)結(jié)構(gòu)基礎(chǔ)上把每寬為8位的十進制數(shù)看成多項式的系數(shù),vector的下標看成多項式的指數(shù),然后再對應相乘相加就可以了,注意系數(shù)超過8位 將超八位的補分進位。

我這里是笛卡爾相乘。一般來說是夠用的。

但其實多項式乘法算法還有很多更高效的。

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

關(guān)于“C++怎么實現(xiàn)大整數(shù)乘法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI