实施BigInteger部门

时间:2015-02-03 08:34:06

标签: c++ algorithm c++11

我使用BigInteger创建了一个std::string类。界面如下:

class BigInteger
{
private:
    char sign;
    std::string digits;
    const std::size_t base = 10;
    short toDigit(int index) const {return index >= 0 && index < digits.size() ? digits[index] - '0' : 0;}

public:
    BigInteger();
    BigInteger(int value);
    BigInteger(int64_t value);
    BigInteger(const std::string &value);
    BigInteger(const BigInteger &other);

    inline bool isNegative() const {return sign == '-';}
    inline bool isPositive() const {return sign == '+';}
    inline bool isNeutral() const {return sign == '~';}

    bool operator < (const BigInteger &other) const;
    bool operator > (const BigInteger &other) const;
    bool operator <= (const BigInteger &other) const;
    bool operator >= (const BigInteger &other) const;
    bool operator == (const BigInteger &other) const;
    bool operator != (const BigInteger &other) const;

    BigInteger& operator = (const BigInteger &other);
    BigInteger& operator += (const BigInteger &other);
    BigInteger& operator -= (const BigInteger &other);
    BigInteger& operator *= (const BigInteger &other);
    BigInteger& operator /= (const BigInteger &other);

    BigInteger operator + (const BigInteger &other) const;
    BigInteger operator - (const BigInteger &other) const;
    BigInteger operator * (const BigInteger &other) const;
    BigInteger operator / (const BigInteger &other) const;

    BigInteger& divide(const BigInteger &D, BigInteger &R);

    friend std::ostream& operator << (std::ostream& os, const BigInteger& other);
};

字符串中的每个字符代表一位数。

我实现了除divide函数和division operator之外的所有运算符。

我被困的地方!我根据维基百科的解释编写了所有算法,并且遇到了我喜欢的除法算法:

https://en.wikipedia.org/wiki/Division_algorithm#Integer_division_.28unsigned.29_with_remainder

我喜欢这个,因为它为我提供了quotientremainder,这将使modulo更容易实现。

但是,我没有移位运算符,我不知道如何将R的最低有效位设置为我的字符串中的分子中的位。我有什么想法可以实现我的divide功能吗?

我试过了:

BigInteger& BigInteger::divide(const BigInteger &D, BigInteger &R)
{
    if (D.isNeutral()) //if D == 0.
    {
        throw std::overflow_error("Division By Zero Exception.");
    }

    R = 0;
    BigInteger Q = 0;

    for (std::size_t I = 0; I < digits.size(); ++I)
    {
        R *= 2; //I believe this is the same as shifting left by 1.
        R.digits[0] = digits[I];
        if (R >= D)
        {
            R -= D;
            Q.digits[I] = '1';
        }
    }
    *this = Q;
    return *this;
}

数字向后存储在字符串中。例如:

值= 1024 digits = 4201

我需要做些什么才能让BitShifting工作并让分部工作?这个部门对我来说更重要。

0 个答案:

没有答案