#include <iostream>
#include <stdexcept>
/*
Integer power function: intpow(base, exponent)
- Computes base^exponent for integer inputs.
- Uses exponentiation by squaring:
• This reduces the number of multiplications dramatically.
• Runs in O(log exponent) time.
- Handles negative bases naturally.
- Rejects negative exponents because the result would be fractional.
(You can extend this if you want integer reciprocals or fixed‑point.)
*/
int intpow(int base, int exp) {
// Guard against negative exponents: not representable as int
if (exp < 0) {
throw std::invalid_argument("intpow: negative exponent not supported");
}
// Fast path: anything to the power of 0 is 1
if (exp == 0) {
return 1;
}
// Use exponentiation by squaring
long long result = 1; // use wider type internally to reduce overflow risk
long long current = base; // current multiplier
while (exp > 0) {
// If the current exponent bit is set, multiply result by current
if (exp & 1) {
result *= current;
}
// Square the current multiplier for the next bit
current *= current;
// Shift exponent right by one bit
exp >>= 1;
}
// Cast back to int; caller is responsible for avoiding overflow
return static_cast<int>(result);
}
/*
Test main
*/
int main() {
std::cout << intpow(2, 3) << std::endl; // 8
std::cout << intpow(3, 3) << std::endl; // 27
std::cout << intpow(3, 2) << std::endl; // 9
std::cout << intpow(2, 2) << std::endl; // 4
std::cout << intpow(5, 2) << std::endl; // 25
std::cout << intpow(-2, 4) << std::endl; // 16
}
/*
run:
8
27
9
4
25
16
*/