Skip to content

Commit 78adb64

Browse files
authored
Fix And Add power.py
To fix the inaccuracies and allow handling of negative exponents and bases, the key issue lies in how negative numbers are handled in the power calculation, especially when dividing. ## Example Output: ```python >>> power(4, 6) 4096 >>> power(2, 3) 8 >>> power(-2, 3) -8 >>> power(2, -3) 0.125 >>> power(-2, -3) -0.125 ```
1 parent e59d819 commit 78adb64

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

divide_and_conquer/power.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,15 @@ def actual_power(a: int, b: int):
1919
"""
2020
if b == 0:
2121
return 1
22+
half = actual_power(a, b // 2)
23+
2224
if (b % 2) == 0:
2325
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
2426
else:
25-
return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
26-
27-
27+
return half * half
28+
else:
29+
return a * half * half
30+
2831
def power(a: int, b: int) -> float:
2932
"""
3033
:param a: The base (integer).

0 commit comments

Comments
 (0)