forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpower_using_iteration.py
More file actions
86 lines (74 loc) · 2.26 KB
/
power_using_iteration.py
File metadata and controls
86 lines (74 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def power(base: float, exponent: int) -> float:
"""
Optimized power function using exponentiation by squaring.
Args:
base (float): The base number.
exponent (int): The exponent.
Returns:
float: The result of base raised to the power of exponent.
Examples:
>>> power(2, 3)
8.0
>>> power(5, -2)
0.04
>>> power(10, 0)
1.0
>>> power(7, 2)
49.0
>>> power(2, -3)
0.125
>>> power(2.5, 4)
39.0625
>>> power(-3.5, 2)
12.25
>>> power(-2, 3)
-8.0
>>> power(0, 5)
0.0
>>> power(0, 1)
0.0
>>> power(0, -1)
Traceback (most recent call last):
...
ZeroDivisionError: 0.0 cannot be raised to a negative power.
>>> power(0, 0)
Traceback (most recent call last):
...
ValueError: 0.0 raised to the power of 0 is indeterminate.
>>> power(1, 1000)
1.0
"""
if base == 0 and exponent == 0:
raise ValueError("0.0 raised to the power of 0 is indeterminate.")
if base == 0 and exponent < 0:
raise ZeroDivisionError("0.0 cannot be raised to a negative power.")
result = 1.0
if exponent < 0:
base = 1 / base
exponent = -exponent
while exponent:
if exponent % 2 == 1:
result *= base
base *= base # Square the base
exponent //= 2 # Halve the exponent
return round(result, 5) # Round to 5 decimal places
if __name__ == "__main__":
import doctest
doctest.testmod()
print("Raise base to the power of exponent using an optimized approach...")
try:
# Input handling and validation
base = float(input("Enter the base: ").strip()) # Supports float & int
exponent = int(
input("Enter the exponent: ").strip()
) # Ensures exponent is an integer
# Calculate result
result = power(base, exponent)
# Display the result
print(f"{base} to the power of {exponent} is {result}")
except ValueError as e:
# Handle invalid input or indeterminate cases
print(e)
except ZeroDivisionError as e:
# Handle division by zero
print(e)