mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-03-12 17:49:50 +00:00
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 ```
This commit is contained in:
parent
e59d819d09
commit
78adb6463f
@ -19,11 +19,14 @@ def actual_power(a: int, b: int):
|
||||
"""
|
||||
if b == 0:
|
||||
return 1
|
||||
half = actual_power(a, b // 2)
|
||||
|
||||
if (b % 2) == 0:
|
||||
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
|
||||
else:
|
||||
return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
|
||||
|
||||
return half * half
|
||||
else:
|
||||
return a * half * half
|
||||
|
||||
def power(a: int, b: int) -> float:
|
||||
"""
|
||||
|
Loading…
x
Reference in New Issue
Block a user