Exemplo n.º 1
0
const BigInteger BigInteger::operator-(const BigInteger &other) const {
	if (Signum() != other.Signum()) {
		return (Signum() == Positive ? Negate() : *this) + (other.Signum() == Positive ? other.Negate() : other);
	}

	if (*this > other) {
		int iterationSize = std::max(Size(), other.Size());
		unsigned short remainder = 0;
		std::vector<unsigned short> digitVector;
		for (int i = 0; i < iterationSize; i++) {
			unsigned short selfDigit = i < Size() ? mDigits[i] : 0;
			unsigned short otherDigit = i < other.Size() ? other.mDigits[i] : 0;
			unsigned short toSubstract = otherDigit + remainder;
			if (selfDigit >= toSubstract) {
				digitVector.push_back(selfDigit - toSubstract);
				remainder = 0;
			} else {
				digitVector.push_back((selfDigit + 10) - toSubstract);
				remainder = 1;
			}
		}
		while (digitVector.at(digitVector.size() - 1) == 0) {
			digitVector.pop_back();
		}
		return BigInteger(Signum(), digitVector.size(), CopyOf(digitVector));
	} else {
		return (other - (*this)).Negate();
	}
}
Exemplo n.º 2
0
bool BigInteger::operator<(const BigInteger &other) const {
	if (Signum() == Positive && other.Signum() == Negative) {
		return false;
	}
	if (Signum() == Negative && other.Signum() == Positive) {
		return true;
	}
	if (Size() < other.Size()) {
		return Signum() == Positive;
	}
	if (Size() > other.Size()) {
		return Signum() == Negative;
	}
	// size of the two are equal, and the sign is also equal
	for (int i = 0; i < Size(); i++) {
		unsigned short selfDigit = mDigits[i];
		unsigned short otherDigit = other.mDigits[i];
		if (selfDigit != otherDigit) {
			return Signum() == Negative ? selfDigit > otherDigit : selfDigit < otherDigit;
		}
	}
	return false;
}
Exemplo n.º 3
0
bool BigInteger::operator==(const BigInteger &other) const {
	if (Signum() != other.Signum()) {
		return false;
	}
	if (Size() != other.Size()) {
		return false;
	}
	for (int i = 0; i < Size(); i++) {
		if (mDigits[i] != other.mDigits[i]) {
			return false;
		}
	}
	return true;
}
Exemplo n.º 4
0
const BigInteger BigInteger::operator+(const BigInteger &other) const {
	if (Signum() != other.Signum()) {
		return *this - other;
	}
	int iterationSize = std::max(Size(), other.Size());
	unsigned short remainder = 0;
	std::vector<unsigned short> digitVector;

	for (int i = 0; i < iterationSize; i++) {
		unsigned short selfDigit = i < Size() ? mDigits[i] : 0;
		unsigned short otherDigit = i < other.Size() ? other.mDigits[i] : 0;
		unsigned short result = selfDigit + otherDigit + remainder;
		remainder = (unsigned short) (result / 10);
		digitVector.push_back(result % 10);
	}

	if (remainder != 0) {
		digitVector.push_back(remainder);
	}

	return BigInteger(Signum(), digitVector.size(), CopyOf(digitVector));
}