File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11def power (base : float , exponent : int ) -> float :
22 """
33 Optimized power function using exponentiation by squaring.
4- It handles both positive and negative exponents efficiently.
5- This function take time complexity O(log n) for exponentiation.
6- space complexity is O(1) as it uses a constant amount of space.
4+
5+ Args:
6+ base (float): The base number.
7+ exponent (int): The exponent.
8+
9+ Returns:
10+ float: The result of base raised to the power of exponent.
11+
12+ Examples:
13+ >>> power(2, 3)
14+ 8.0
15+ >>> power(5, -2)
16+ 0.04
17+ >>> power(10, 0)
18+ 1.0
19+ >>> power(7, 2)
20+ 49.0
21+ >>> power(2, -3)
22+ 0.125
23+ >>> power(2.5, 4)
24+ 39.0625
25+ >>> power(-3.5, 2)
26+ 12.25
27+ >>> power(-2, 3)
28+ -8.0
29+ >>> power(0, 5)
30+ 0.0
31+ >>> power(0, 0)
32+ 1.0
33+ >>> power(0, -1)
34+ Traceback (most recent call last):
35+ ...
36+ ZeroDivisionError: 0.0 cannot be raised to a negative power.
37+ >>> power(1, 1000)
38+ 1.0
39+
740 """
8- # Handle negative exponents by taking reciprocal of the base
41+ result = 1.0
942 if exponent < 0 :
1043 base = 1 / base
1144 exponent = - exponent
12-
13- result = 1
14- # Use exponentiation by squaring for efficiency
1545 while exponent :
16- if exponent % 2 == 1 : # If the current exponent is odd
46+ if exponent % 2 == 1 :
1747 result *= base
1848 base *= base # Square the base
1949 exponent //= 2 # Halve the exponent
@@ -22,7 +52,6 @@ def power(base: float, exponent: int) -> float:
2252
2353if __name__ == "__main__" :
2454 import doctest
25-
2655 doctest .testmod ()
2756 print ("Raise base to the power of exponent using an optimized approach..." )
2857
You can’t perform that action at this time.
0 commit comments