Prompt: Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example:
Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Solution: First, we have to think of examples of the problem like so:
If b is even:
ab = a(b/2) * a(b/2)
ab = (ab/2)2
If b is odd:
ab = a(b/2) * a(b/2) * a
ab = (ab/2)2 * a
Then, we can solve this with either a recursion method or iterative method. The base case for this solution would be a0 = 1 because b keeps dividing by 2. The runtime would be O(log n) because b keeps dividing by 2 until 0. We want to use the iterative method since iterative programs are faster than recursive ones.