- 加法操作算法
- 按位对齐
- 低位开始逐位相加
- 进位调整
- 减法操作算法
- 按位对齐
- 低位开始逐位相减
- 借位调整
- 乘法操作算法
- 乘数与被乘数二层嵌套循环
- 结果按照
res[i+j] += a[i]*b[j]
方式存储 - 进位调整。
- 除法操作算法
- 测算被除数和除数的长度
- 高位开始 ,对位做减法 ,并完成借位
- 高位开始逐位计算商
- 整理商 , 产生余数
- 比较运算符
bool operator < (bignum const& right)const{
if(this == &right){
return false;
}
if(right.nums_.size() > nums_.size()){
return true;
}else if(right.nums_.size() < nums_.size()){
return false;
}else{
pair<
vector<int>::const_reverse_iterator,
vector<int>::const_reverse_iterator
> p = mismatch(nums_.rbegin(),nums_.rend(),right.nums_.rbegin());
return *(p.first) < *(p.second);
}
}
- 加法操作
基础实现
bignum operator+(bignum const& right)const{
bignum maxbn = max(*this,right);
bignum minbn = min(*this,right);
minbn.nums_.resize(maxbn.nums_.size());
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
minbn.nums_.begin(),maxbn.nums_.begin(),plus<int>());
for(size_t i=0,size = maxbn.nums_.size();i<size;i++){
int res = maxbn.nums_[i]/10;
if(res > 0 and i == size-1){
maxbn.nums_.push_back(res);
}else{
maxbn.nums_[i+1] += res;
}
maxbn.nums_[i] %= 10;
}
return maxbn;
}
C++03仿函数实现
class Carry{
public:
Carry(int& c):carry_(c){}
int operator()(int n){
n += carry_;
carry_ = n/10;
return n%10;
}
private:
int& carry_;
};
bignum operator+(bignum const& right)const{
bignum maxbn = max(*this,right);
bignum minbn = min(*this,right);
minbn.nums_.resize(maxbn.nums_.size());
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
minbn.nums_.begin(),maxbn.nums_.begin(),plus<int>());
int carry = 0;
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
maxbn.nums_.begin(),Carry(carry));
if(carry > 0){
maxbn.nums_.push_back(carry);
}
return maxbn;
}
C++11 lambda表达式实现
bignum operator+(bignum const& right)const{
bignum maxbn = max(*this,right);
bignum minbn = min(*this,right);
minbn.nums_.resize(maxbn.nums_.size());
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
minbn.nums_.begin(),maxbn.nums_.begin(),plus<int>());
int carry = 0;
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
maxbn.nums_.begin(),[&carry](int n){
n += carry;
carry = n/10;
return n%10;
});
if(carry > 0){
maxbn.nums_.push_back(carry);
}
return maxbn;
}
Boost lambda表达式实现方式
#include <boost/lambda/lambda.hpp>
using namespace boost::lambda;
// ...
bignum operator+(bignum const& right)const{
bignum maxbn = max(*this,right);
bignum minbn = min(*this,right);
minbn.nums_.resize(maxbn.nums_.size());
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
minbn.nums_.begin(),maxbn.nums_.begin(),plus<int>());
int carry = 0;
transform(maxbn.nums_.begin(),maxbn.nums_.end(),
maxbn.nums_.begin(),(_1+=var(carry),var(carry)=_1/10,_1%10));
if(carry > 0){
maxbn.nums_.push_back(carry);
}
return maxbn;
}