Esempio n. 1
0
//二分探商优化 效率比短除法大大提高...
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;
}
Esempio n. 2
0
//各种关系运算符
bool LongInt::operator < (const LongInt &obj) const{
    if(n.back()<0 and obj.n.back()>=0)
        return true;
    else if(n.back() >=0 and obj.n.back()<0)
        return false;
    else if(n.back() <0 and obj.n.back()<0 )
        return !(this->getABS() < obj.getABS());//递归
    else if(n.back() >= 0 and obj.n.back() >=0){
       if(n.size() != obj.n.size())
           return n.size() < obj.n.size();
        for (int k = n.size() -1 ; k>=0; --k) {
            if( n[k] != obj.n[k] )
                return n[k] < obj.n[k];
        }
    }
    return false;
}
Esempio n. 3
0
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;
}