From 31dcb91a2666158414c28c724029543aa9069a36 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Mon, 23 Aug 2021 16:38:25 +0200 Subject: [PATCH] abacus: bignum: add log10 --- src/bignum/bignum.cc | 18 ++++++++++++++++++ src/bignum/bignum.hh | 2 ++ tests/unit/bignum.cc | 20 ++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/src/bignum/bignum.cc b/src/bignum/bignum.cc index 677191b..db9c922 100644 --- a/src/bignum/bignum.cc +++ b/src/bignum/bignum.cc @@ -492,4 +492,22 @@ BigNum log2(BigNum const& num) { return res; } +BigNum log10(BigNum const& num) { + assert(num.is_canonicalized()); + assert(BASE == 10); + + if (num.is_zero()) { + throw std::invalid_argument("attempt to take the log10 of zero"); + } else if (num.is_negative()) { + throw std::invalid_argument( + "attempt to take the log10 of a negative number"); + } + + auto res = BigNum(num.digits_.size() - 1); + + assert(res.is_canonicalized()); + + return res; +} + } // namespace abacus::bignum diff --git a/src/bignum/bignum.hh b/src/bignum/bignum.hh index 1c5529e..6a7a009 100644 --- a/src/bignum/bignum.hh +++ b/src/bignum/bignum.hh @@ -93,6 +93,8 @@ public: friend BigNum log2(BigNum const& num); + friend BigNum log10(BigNum const& num); + friend bool operator==(BigNum const& lhs, BigNum const& rhs) { return lhs.equal(rhs); } diff --git a/tests/unit/bignum.cc b/tests/unit/bignum.cc index 61ae839..f584778 100644 --- a/tests/unit/bignum.cc +++ b/tests/unit/bignum.cc @@ -397,3 +397,23 @@ TEST(BigNum, log2) { EXPECT_EQ(log2(eight), three); EXPECT_EQ(log2(nine), three); } + +TEST(BigNum, log10) { + auto const zero = BigNum(0); + auto const one = BigNum(1); + auto const two = BigNum(2); + auto const nine = BigNum(9); + auto const ten = BigNum(10); + auto const eleven = BigNum(11); + auto const ninety_nine = BigNum(99); + auto const hundred = BigNum(100); + auto const hundred_one = BigNum(101); + + EXPECT_EQ(log10(one), zero); + EXPECT_EQ(log10(nine), zero); + EXPECT_EQ(log10(ten), one); + EXPECT_EQ(log10(eleven), one); + EXPECT_EQ(log10(ninety_nine), one); + EXPECT_EQ(log10(hundred), two); + EXPECT_EQ(log10(hundred_one), two); +}