DevPath

← All problems

Integer Power

Medium math · recursion

Description

Return x raised to the power n for non-negative integer n, without using a built-in power operator for large n.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account