算法竞赛入门经典 这本书并没有对大数乘法实现,所以自己补充了一下,乘法的实现很简单,就是再其数据结构基础上把每宽为8位的十进制数看成多项式的系数,vector的下标看成多项式的指数,然后再对应相乘相加就可以了,注意系数超过8位 将超八位的补分进位。
我这里是笛卡尔相乘。一般来说是够用的。
但其实多项式乘法算法还有很多更高效的。
#include
#include
#include
#include
using namespace std;
typedef long long LL;
struct BigInteger{
static const int BASE = 100000000;
static const int WIDTH = 8;
vector s;
BigInteger operator = (const string& str){
s.clear();
int x, len=(str.length()-1)/WIDTH+1;
for(int i=0;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
for(int i=0;i
for(int j=0;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
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<
int len=b.s.size();
out<
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
if(b.s[i])out<
}
return out;
}
int main()
{
int n;BigInteger b;
b="1000000000000";
cout<< b<
cout<< (b*b)*4*b*b <
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。