Problem List

Pow(x, n)

May 31, 2025Go math, recursionmedium

Problem

Approach

My Saving Grace

By some miracle, my Algorithms Professor happended to be covering this exact formula in class just a few days ago. And I remembered it enough to grind through the problem.
Exponentiation
Exponentiation

Edge Cases

Reflections

I would have absolutely tried to brute force it with a recurrence relation had I not seen the exact formula just a couple days before.

Performance

Complexity

Go Solution
func myPow(x float64, n int) float64 {
    if n <= 1 {
        return baseCase(x,n)
    }

    if isEven(n) {
        return myPow(x*x, n / 2)
    }
    
    return myPow(x*x, n / 2) * x
}

func isEven(n int) bool {
    return n % 2 == 0 
}

func baseCase(x float64, n int) float64 {
    if n < 0 {
        return myPow(1/x, n * -1)
    }

    if n == 0 {
        return 1
    }

    return x
}
LeetCode Problem Link