//二分探商优化 效率比短除法大大提高... LongInt LongInt::operator / (const LongInt &obj) const{ assert(obj!=0 && "devide zero"); bool negative = (*this<0 and obj>0) or (*this>0 and obj<0); LongInt a = this->getABS() , b = obj.getABS(); //两类特殊情况 if(a < b) return 0; if(a == b) return negative ? -1 : 1; LongInt lft = 1, rgt = a; LongInt curSum = lft + a; LongInt middle = curSum.divBy2(); LongInt one = 1; //开始二分 while( not(a >= middle * b and a < (b + middle * b) )){ if(middle * b < a) //探商 lft = middle + one; else rgt = middle; curSum = lft + rgt; middle = curSum.divBy2(); } return negative ? middle.getOpposite() : middle; }
LongInt LongInt::operator - (const LongInt& obj) const{ LongInt result; result.n.clear(); if(*this == obj) result = 0; else{ //两个都是非负数时 if(*this >=0 and obj >= 0){ if(*this > obj){ for (int i = 0, r = 0;; ++i) { if(not r and i>= n.size() and i>= obj.n.size()) break; int t = r; if(i < n.size()) t += n[i]; if(i < obj.n.size()) t -= obj.n[i]; if(t < 0){ t += _base; r = -1; //进位 }else{ r = 0; } result.n.push_back(t); } //除去前位0 while(not result.n.back() and not result.n.empty()) result.n.pop_back(); if(result.n.empty()) result.n.push_back(0); //如果就是0 则补回一个 }else{ result = (obj - *this).getOpposite(); } } else if(*this>=0 and obj<0) result = *this + obj; else if(*this<0 and obj>=0) result = (this->getOpposite() + obj).getOpposite(); else if(*this<0 and obj<0) //递归即可 result = obj.getOpposite() - this->getOpposite(); } return result; }
LongInt LongInt::operator * (const LongInt& obj) const{ //乘法的处理 也要考虑不同的符号 LongInt result; result.n.clear(); result = 0; LongInt a = this->getABS(); LongInt b = obj.getABS(); bool negative = (*this<0 and obj>0) or (*this>0 and obj<0); if (*this==0 or obj==0) return 0; for (int i=0;i<obj.n.size();++i) { LongInt midRes;//临时中间变量 midRes.n.clear(); if (i)//如果i大于0 for (int j=1;j<=i;++j) midRes.n.push_back(0); unsigned long long r = 0;//中间余数 for (int j = 0; ; ++j) { if (r == 0 && j >= n.size() ) break; else{ unsigned long long t = r; if (j < n.size()) t += (long long int)a.n[j] * b.n[i]; midRes.n.push_back(t % _base); r = t / _base; } } result += midRes; } return negative ? result.getOpposite() : result; }
//各种算法运算符 LongInt LongInt::operator + (const LongInt& obj) const{ LongInt result; result.n.clear(); if(*this >= 0 and obj >= 0){//两个非负整数相加才是真正的相加 否则转移为减法处理 for (int i = 0, r = 0; ; ++i) { if(r==0 and i>=n.size() and i>=obj.n.size()) break; int t = r; if(i < n.size()) t += n[i]; if(i < obj.n.size()) t += obj.n[i]; result.n.push_back(t % _base); r = t / _base; } }else if(*this < 0 and obj < 0) result = (this->getABS() + this->getABS()).getOpposite(); else if(*this < 0 and obj >= 0) result = obj - this->getOpposite(); else if(*this >= 0 and obj < 0) result = *this - obj.getOpposite(); return result; }