Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn). This function should handle both positive and negative values of n
.
For example:
Consider the following constraints:
Discuss:
Provide code implementation for the solution.
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
We need to calculate x raised to the power of n. The brute force way means directly multiplying x by itself n times. This is like repeatedly adding something to itself a specific number of times.
Here's how the algorithm would work step-by-step:
def power(base, exponent):
result = 1
if exponent > 0:
for _ in range(exponent):
result *= base
elif exponent == 0:
# Anything to the power of 0 is 1
return 1
else:
# Handle negative exponents by inverting the base
inverted_base = 1 / base
for _ in range(abs(exponent)):
result *= inverted_base
return result
Instead of repeatedly multiplying a number by itself, which can take a long time especially for large exponents, we use a 'divide and conquer' strategy. We break down the exponent into smaller parts, calculate the powers for those parts, and then combine them efficiently to get the final result. This clever approach dramatically reduces the number of calculations needed.
Here's how the algorithm would work step-by-step:
def power(base, exponent):
if exponent == 0:
return 1.0
if exponent == 1:
return base
# Handle negative exponents by inverting the base.
if exponent < 0:
base = 1 / base
exponent = -exponent
result = 1.0
current_power_of_base = base
# Iterate through the bits of the exponent.
while exponent > 0:
# If the current bit is 1, multiply the result.
if exponent % 2 == 1:
result *= current_power_of_base
# Square the base for the next power of 2.
current_power_of_base *= current_power_of_base
exponent //= 2
return result
Case | How to Handle |
---|---|
n = 0 | Any number to the power of 0 is 1, so return 1.0. |
x = 0 and n < 0 | Division by zero error will occur, so throw an exception or return a predefined error value (e.g., Infinity, NaN). |
n = Integer.MIN_VALUE | Negating Integer.MIN_VALUE will cause integer overflow, so handle by converting n to a long and then negating. |
x = 1 | 1 to any power is 1, so return 1.0. |
x = -1 and n is odd | The result will be -1, so return -1.0. |
x = -1 and n is even | The result will be 1, so return 1.0. |
n is negative | Calculate x to the power of absolute value of n, then return 1 divided by the result. |
Floating point precision issues with large n | Ensure algorithm is efficient (logarithmic time) to avoid excessive multiplication and thus reduce floating-point errors accumulation. |