abacus: bignum: add order comparisons

This commit is contained in:
Bruno BELANYI 2021-08-20 17:01:21 +02:00
parent 17bd51d197
commit 2600eb2ba7
2 changed files with 30 additions and 0 deletions

View file

@ -38,6 +38,19 @@ bool BigNum::equal(BigNum const& rhs) const {
return digits_ == rhs.digits_; return digits_ == rhs.digits_;
} }
bool BigNum::less_than(BigNum const& rhs) const {
assert(is_canonicalized());
assert(rhs.is_canonicalized());
if (sign_ != rhs.sign_) {
return sign_ < rhs.sign_;
}
return std::lexicographical_compare(digits_.rbegin(), digits_.rend(),
rhs.digits_.rbegin(),
rhs.digits_.rend());
}
void BigNum::canonicalize() { void BigNum::canonicalize() {
auto const it = std::find_if(digits_.rbegin(), digits_.rend(), auto const it = std::find_if(digits_.rbegin(), digits_.rend(),
[](auto v) { return v != 0; }); [](auto v) { return v != 0; });

View file

@ -18,8 +18,25 @@ public:
return !(lhs == rhs); return !(lhs == rhs);
} }
friend bool operator<(BigNum const& lhs, BigNum const& rhs) {
return lhs.less_than(rhs);
}
friend bool operator>(BigNum const& lhs, BigNum const& rhs) {
return rhs < lhs;
}
friend bool operator<=(BigNum const& lhs, BigNum const& rhs) {
return !(lhs > rhs);
}
friend bool operator>=(BigNum const& lhs, BigNum const& rhs) {
return !(lhs < rhs);
}
private: private:
bool equal(BigNum const& rhs) const; bool equal(BigNum const& rhs) const;
bool less_than(BigNum const& rhs) const;
void canonicalize(); void canonicalize();
bool is_canonicalized() const; bool is_canonicalized() const;