Integer Power
Medium math · recursion
Description
Constraints
0 <= n <= 30; small base
Examples
Input: x = 2, n = 10
Output: 1024
Hints (1)
- Exponentiation by squaring halves the exponent each step.
Solutions
Exponentiation by squaring. · Time O(log n) · Space O(1)
func intPow(x, n int) int {
result, base := 1, x
for n > 0 {
if n%2 == 1 {
result *= base
}
base *= base
n /= 2
}
return result
}
Exponentiation by squaring. · Time O(log n) · Space O(1)
function intPow(x, n) {
let result = 1, base = x;
while (n > 0) {
if (n % 2 === 1) result *= base;
base *= base;
n = Math.floor(n / 2);
}
return result;
}
Exponentiation by squaring. · Time O(log n) · Space O(1)
function intPow($x, $n) {
$result = 1;
$base = $x;
while ($n > 0) {
if ($n % 2 === 1) { $result *= $base; }
$base *= $base;
$n = intdiv($n, 2);
}
return $result;
}
Exponentiation by squaring. · Time O(log n) · Space O(1)
def intPow(x, n):
result = 1
base = x
while n > 0:
if n % 2 == 1:
result *= base
base *= base
n //= 2
return result
Exponentiation by squaring. · Time O(log n) · Space O(1)
function intPow(x: number, n: number): number {
let result = 1, base = x;
while (n > 0) {
if (n % 2 === 1) result *= base;
base *= base;
n = Math.floor(n / 2);
}
return result;
}
Create a free account to submit solutions, track progress and save problems.
Create account