這篇文章給大家介紹C++中怎么實(shí)現(xiàn)一個(gè)大整數(shù)乘法,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

成都創(chuàng)新互聯(lián)歡迎咨詢:18982081108,為您提供成都網(wǎng)站建設(shè)網(wǎng)頁設(shè)計(jì)及定制高端網(wǎng)站建設(shè)服務(wù),成都創(chuàng)新互聯(lián)網(wǎng)頁制作領(lǐng)域十年,包括成都集裝箱等多個(gè)方面擁有豐富的網(wǎng)站維護(hù)經(jīng)驗(yàn),選擇成都創(chuàng)新互聯(lián),為企業(yè)保駕護(hù)航!
算法競賽入門經(jīng)典 這本書并沒有對大數(shù)乘法實(shí)現(xiàn),所以自己補(bǔ)充了一下,乘法的實(shí)現(xiàn)很簡單,就是再其數(shù)據(jù)結(jié)構(gòu)基礎(chǔ)上把每寬為8位的十進(jìn)制數(shù)看成多項(xiàng)式的系數(shù),vector的下標(biāo)看成多項(xiàng)式的指數(shù),然后再對應(yīng)相乘相加就可以了,注意系數(shù)超過8位 將超八位的補(bǔ)分進(jìn)位。
#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++中怎么實(shí)現(xiàn)一個(gè)大整數(shù)乘法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
新聞標(biāo)題:C++中怎么實(shí)現(xiàn)一個(gè)大整數(shù)乘法
當(dāng)前URL:http://chinadenli.net/article44/jpcgee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、品牌網(wǎng)站建設(shè)、App設(shè)計(jì)、關(guān)鍵詞優(yōu)化、網(wǎng)站制作、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)