Calculate Power (x^n)
Efficiently calculating powers is a fundamental operation in computer science, underpinning various algorithms from cryptography to numerical analysis. A naive multiplication approach can be prohibitively slow for large exponents. This problem challenges you to implement an optimized power function using a Divide and Conquer strategy.
Implement the myPow(x, n) function, which calculates x raised to the power n.
Your solution should:
Function Signature:
function myPow(x: number, n: number): number
Parameters:
x: A number (float) representing the base.n: A non-negative number (integer) representing the exponent.Return Value:
number representing x raised to the power n (x^n).n will always be a non-negative integer.x = 0 and n = 0, the result should be 1.0 (following common programming library conventions like Math.pow(0, 0)).number type precision is sufficient.Examples
Example 1
Input:
x = 2.00000, n = 10
Output:
1024.00000
Note:
2^10 = 1024
Example 2
Input:
x = 2.10000, n = 3
Output:
9.26100
Note:
2.1^3 = 9.261
Example 3
Input:
x = 0.00000, n = 0
Output:
1.00000
Note:
By convention, 0^0 is 1.
Example 4
Input:
x = 1.00000, n = 1000000
Output:
1.00000
Note:
1 raised to any power is 1.
Constraints
-100.0 < x < 100.00 <= n <= 10^9[-10^9, 10^9] and can be accurately represented by a standard double-precision floating-point number.O(log n) time complexity.O(log n) space complexity (due to recursion stack) or O(1) if an iterative approach is used.n < 0).n=0 and x=0.O(log n) time complexity.Loading editor...