Skip to content

Commit 338cbaf

Browse files
lighting9999pre-commit-ci[bot]MaximSmolskiy
authored
Improve power.py (TheAlgorithms#12567)
* 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 ``` * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update power.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update power.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update power.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update power.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent e59d819 commit 338cbaf

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

divide_and_conquer/power.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
def actual_power(a: int, b: int):
1+
def actual_power(a: int, b: int) -> int:
22
"""
33
Function using divide and conquer to calculate a^b.
44
It only works for integer a,b.
@@ -19,10 +19,12 @@ 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:
23-
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
25+
return half * half
2426
else:
25-
return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
27+
return a * half * half
2628

2729

2830
def power(a: int, b: int) -> float:
@@ -43,9 +45,9 @@ def power(a: int, b: int) -> float:
4345
-0.125
4446
"""
4547
if b < 0:
46-
return 1 / actual_power(a, b)
48+
return 1 / actual_power(a, -b)
4749
return actual_power(a, b)
4850

4951

5052
if __name__ == "__main__":
51-
print(power(-2, -3))
53+
print(power(-2, -3)) # output -0.125

0 commit comments

Comments
 (0)