Skip to content

Commit ee3f4be

Browse files
committed
Added iterative solution for power calculation
1 parent 89ad00e commit ee3f4be

1 file changed

Lines changed: 38 additions & 9 deletions

File tree

maths/power_using_iteration.py

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,49 @@
11
def 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

2353
if __name__ == "__main__":
2454
import doctest
25-
2655
doctest.testmod()
2756
print("Raise base to the power of exponent using an optimized approach...")
2857

0 commit comments

Comments
 (0)