From 78adb6463f683c7f74c9f854a46bf371e005a25c Mon Sep 17 00:00:00 2001 From: lighting9999 <120090117+lighting9999@users.noreply.github.com> Date: Sat, 8 Feb 2025 17:48:46 +0800 Subject: [PATCH] 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 ``` --- divide_and_conquer/power.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/divide_and_conquer/power.py b/divide_and_conquer/power.py index faf6a3476..3370b08d2 100644 --- a/divide_and_conquer/power.py +++ b/divide_and_conquer/power.py @@ -19,12 +19,15 @@ 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: """ :param a: The base (integer).