abacus: bignum: add log2
This commit is contained in:
parent
4b85d22923
commit
c730705a13
3 changed files with 47 additions and 0 deletions
|
|
@ -468,4 +468,28 @@ BigNum sqrt(BigNum const& num) {
|
|||
return res;
|
||||
}
|
||||
|
||||
BigNum log2(BigNum const& num) {
|
||||
assert(num.is_canonicalized());
|
||||
|
||||
if (num.is_zero()) {
|
||||
throw std::invalid_argument("attempt to take the log2 of zero");
|
||||
} else if (num.is_negative()) {
|
||||
throw std::invalid_argument(
|
||||
"attempt to take the log2 of a negative number");
|
||||
}
|
||||
|
||||
auto tmp = num;
|
||||
auto res = BigNum(0);
|
||||
auto one = BigNum(1);
|
||||
|
||||
while (tmp > one) {
|
||||
tmp.digits_ = do_halve(tmp.digits_);
|
||||
res += one;
|
||||
}
|
||||
|
||||
assert(res.is_canonicalized());
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace abacus::bignum
|
||||
|
|
|
|||
|
|
@ -91,6 +91,8 @@ public:
|
|||
|
||||
friend BigNum sqrt(BigNum const& num);
|
||||
|
||||
friend BigNum log2(BigNum const& num);
|
||||
|
||||
friend bool operator==(BigNum const& lhs, BigNum const& rhs) {
|
||||
return lhs.equal(rhs);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue