2023-09-20 16:47:36 +08:00
|
|
|
/**
|
|
|
|
* @file
|
|
|
|
* @brief Calculates the nth power of a number in O(log(n)) time.
|
|
|
|
* @details
|
|
|
|
* Calculating the nth power of a number requires O(n) time using the naive
|
|
|
|
* method. This algorithm optimizes it through exponentiation by squaring.
|
|
|
|
* https://cp-algorithms.com/algebra/binary-exp.html
|
|
|
|
* @author [Praneeth Jain](https://github.com/PraneethJain)
|
|
|
|
*/
|
|
|
|
|
2023-10-02 14:22:43 +08:00
|
|
|
#include <assert.h> /// for assert()
|
|
|
|
#include <stdint.h> /// for int64 types
|
|
|
|
#include <stdio.h> /// for output
|
|
|
|
#include <stdlib.h> /// for exit()
|
2023-09-20 16:47:36 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @brief Determines a raised to the nth power via binary exponentiation.
|
|
|
|
* @param a - base
|
|
|
|
* @param n - exponent
|
|
|
|
* @return a raised to the nth power
|
|
|
|
* @warning
|
2023-09-28 02:02:02 +08:00
|
|
|
* can overflow very quickly.
|
2023-09-20 16:47:36 +08:00
|
|
|
*/
|
2023-09-28 02:02:02 +08:00
|
|
|
int64_t binary_exponentiation(int64_t a, uint64_t n)
|
2023-09-20 16:47:36 +08:00
|
|
|
{
|
2023-09-28 02:02:02 +08:00
|
|
|
int64_t res = 1;
|
2023-09-20 16:47:36 +08:00
|
|
|
while (n > 0)
|
|
|
|
{
|
|
|
|
if (n % 2 == 1) // If the current bit is 1
|
|
|
|
{
|
|
|
|
res *= a; // Then it must be multiplied to the result
|
|
|
|
}
|
|
|
|
|
|
|
|
a *= a; // Square the base
|
|
|
|
n >>= 1; // Move to the next bit
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @brief self-test implementation
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
static void tests()
|
|
|
|
{
|
|
|
|
assert(binary_exponentiation(5, 3) == 125);
|
|
|
|
assert(binary_exponentiation(-7, 3) == -343);
|
|
|
|
assert(binary_exponentiation(9, 0) == 1);
|
|
|
|
assert(binary_exponentiation(-123, 0) == 1);
|
|
|
|
assert(binary_exponentiation(3, 5) == 243);
|
|
|
|
assert(binary_exponentiation(-4, 5) == -1024);
|
|
|
|
|
|
|
|
printf("All tests have successfully passed!\n");
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @brief Main function
|
|
|
|
* @return 0 on exit
|
|
|
|
*/
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
tests(); // run self-test implementations
|
|
|
|
return 0;
|
|
|
|
}
|