C++中怎么实现一个大整数乘法

发布时间:2021-08-07 14:33:40 作者:Leah
来源:亿速云 阅读:134

这篇文章给大家介绍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++中怎么实现一个大整数乘法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 利用Python怎么实现一个大整数乘法算法
  2. C++实现大整数乘法(字符串乘法)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:android中怎么实现倒计时功能

下一篇:如何解决某些HTML字符打不出来的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》