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

專注于為中小企業提供網站設計、網站制作服務,電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業岷縣免費做網站提供優質的服務。我們立足成都,凝聚了一批互聯網行業人才,有力地推動了千余家企業的穩健成長,幫助中小企業通過網站建設實現規模擴充和轉變。
算法競賽入門經典 這本書并沒有對大數乘法實現,所以自己補充了一下,乘法的實現很簡單,就是再其數據結構基礎上把每寬為8位的十進制數看成多項式的系數,vector的下標看成多項式的指數,然后再對應相乘相加就可以了,注意系數超過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;
}關于“C++怎么實現大整數乘法”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
名稱欄目:C++怎么實現大整數乘法
文章源于:http://www.yijiale78.com/article16/ihopdg.html
成都網站建設公司_創新互聯,為您提供手機網站建設、網站導航、響應式網站、靜態網站、外貿建站、面包屑導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯