看了刘佳汝写的那本算法竞赛入门经典第二版里面那个C++的BigInteger,只给出了+号,<<,>>的重载,求一个*,/的重载代码,像他那样写的,用vector解决的
struct BigInteger
{
static const int BASE=100000000;
static const int WIDTH=1;
vectors;
BigInteger(long long num=0) {*this=num;}
BigInteger operator=(long long num) {
s.clear();
do{
s.push_back(num%BASE);
num/=BASE;
}while(num>0);
return *this;
}
BigInteger operator =(const string&str){
s.clear();
int x,len=(str.length()-1)/WIDTH+1;
for(int i=0;i int end=str.length()-i*WIDTH;
int start=max(0,end-WIDTH);
sscanf(str.substr(start,end-start).c_str(),"%d",&x);
s.push_back(x);
}
return *this;
}
BigInteger operator +(const BigInteger &b)const{
BigInteger c;
c.s.clear();
for(int i=0,g=0;;i++)
{
if(g==0&&i>=s.size()&&i>=b.s.size()) break;
int x=g;
if(i<s.size()) x+=s[i];
if(i<b.s.size()) x+=b.s[i];
c.s.push_back(x%BASE);
g=x/BASE;
}
return c;
}
}
http://blog.csdn.net/yang_7_46/article/details/9897563
http://blog.csdn.net/delacroix_xu/article/details/6795807
//乘法这么写
//除法太麻烦了不会
//vectors不太会用,不知道 bigout.s[oi] = .....能不能这么写;
//但算法应该是正确的,
//楼上引用的算法有点问题的,在多次相加有可能会超出 BASE 这个值.
BigInteger operator *(const BigInteger &b)const{
BigInteger bigout;
bigout.s.clear();
for (int i = 0; i < s.size(); i++)
{
if (s[i]){
for (int j = 0; j < b.s.size(); j++){
if (b.s[i]){
long long llo = (long long)(s[i]) * b.s[j];
for (int oi = bigout.s.size(); oi bigout.s.push(0);
for (int oi = i + j; llo>0; oi++)
{
if (oi < bigout.s.size()){
llo += bigout.s[oi];
bigout.s[oi] = llo % BASE;
}else
bigout.s.push(llo % BASE);
llo /= BASE;
}
}
}
}
}
return bigout;
}
奇怪,怎么老是缺少符号??这个补上
BigInteger operator *(const BigInteger &b)const{
BigInteger bigout;
bigout.s.clear();
for (int i = 0; i < s.size(); i++)
{
if (s[i]){
for (int j = 0; j < b.s.size(); j++){
if (b.s[i]){
long long llo = (long long)(s[i]) * b.s[j];
for (int oi = bigout.s.size(); oi < i + j; oi++){
bigout.s.push(0);
}
for (int oi = i + j; llo > 0; oi++)
{
if (oi < bigout.s.size()){
llo += bigout.s[oi];
bigout.s[oi] = llo % BASE;
}else
bigout.s.push(llo % BASE);
llo /= BASE;
}
}
}
}
}
return bigout;
}
//.....
BigInteger operator *(const BigInteger &b)const{
BigInteger bigout;
bigout.s.clear();
for (int i = 0; i < s.size(); i++)
{
if (s[i]){
for (int j = 0; j < b.s.size(); j++){
if (b.s[j]){
long long llo = (long long)(s[i]) * b.s[j];
for (int oi = bigout.s.size(); oi < i + j; oi++){
bigout.s.push(0);
}
for (int oi = i + j; llo > 0; oi++)
{
if (oi < bigout.s.size()){
llo += bigout.s[oi];
bigout.s[oi] = llo % BASE;
}else
bigout.s.push(llo % BASE);
llo /= BASE;
}
}
}
}
}
return bigout;
}