Function to calculate x raised to the power n (i.e., x^n) where x is a float number and n is an integer and it will return float value Example 1: Input: x = 2.00000, n = 10 Output: 1024.0 Example 2: Input: x = 2.10000, n = 3 Output: 9.261000000000001 Example 3:
(x: float, n: int)
| 5 | |
| 6 | |
| 7 | def binaryExponentiation(x: float, n: int) -> float: |
| 8 | """ |
| 9 | Function to calculate x raised to the power n (i.e., x^n) where x is a float number and n is an integer and it will return float value |
| 10 | |
| 11 | Example 1: |
| 12 | |
| 13 | Input: x = 2.00000, n = 10 |
| 14 | Output: 1024.0 |
| 15 | Example 2: |
| 16 | |
| 17 | Input: x = 2.10000, n = 3 |
| 18 | Output: 9.261000000000001 |
| 19 | |
| 20 | Example 3: |
| 21 | |
| 22 | Input: x = 2.00000, n = -2 |
| 23 | Output: 0.25 |
| 24 | Explanation: 2^-2 = 1/(2^2) = 1/4 = 0.25 |
| 25 | """ |
| 26 | |
| 27 | if n == 0: |
| 28 | return 1 |
| 29 | |
| 30 | # Handle case where, n < 0. |
| 31 | if n < 0: |
| 32 | n = -1 * n |
| 33 | x = 1.0 / x |
| 34 | |
| 35 | # Perform Binary Exponentiation. |
| 36 | result = 1 |
| 37 | while n != 0: |
| 38 | # If 'n' is odd we multiply result with 'x' and reduce 'n' by '1'. |
| 39 | if n % 2 == 1: |
| 40 | result *= x |
| 41 | n -= 1 |
| 42 | # We square 'x' and reduce 'n' by half, x^n => (x^2)^(n/2). |
| 43 | x *= x |
| 44 | n //= 2 |
| 45 | return result |
| 46 | |
| 47 | |
| 48 | if __name__ == "__main__": |