From 9d2f0822c338425c961c5c3e95e004019c97ccaf Mon Sep 17 00:00:00 2001 From: Captain ALM Date: Mon, 15 Aug 2022 15:08:54 +0100 Subject: [PATCH] Exponentiation By Squaring. --- main.cpp | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/main.cpp b/main.cpp index 73ff9c6..307289f 100644 --- a/main.cpp +++ b/main.cpp @@ -1,21 +1,30 @@ #include +#include // for std::int64_t +#include // for assert -int getValue() +std::int64_t powint(std::int64_t base, int exp) { - std::cout << "Enter an integer: "; + assert(exp >= 0 && "powint: exp parameter has negative value"); - int x{}; - std::cin >> x; - return x; + std::int64_t result{ 1 }; + while (exp) + { + if (exp & 1) { + std::cout << "a : " << result << "\n"; + result *= base; + } + std::cout << "b : " << exp << "\n"; + exp >>= 1; + std::cout << "c : " << base << "\n"; + base *= base; + } + + return result; } int main() { - int a{ getValue() }; - int b{ getValue() }; - int c{ getValue() }; + std::cout << powint(7, 12); // 7 to the 12th power - std::cout << a + (b * c); // order of eval doesn't matter now - - return 0; + return 0; }