From bb1db01bc6bf578d525b0f0d934de34857964b1e Mon Sep 17 00:00:00 2001 From: Phantasmal24 Date: Wed, 8 Oct 2025 11:41:22 +0530 Subject: [PATCH] Fixed Issues --- calculator.py | 41 +++++++++++++---------------------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/calculator.py b/calculator.py index 02a21ce..2308874 100644 --- a/calculator.py +++ b/calculator.py @@ -1,7 +1,5 @@ def add(a, b): # ISSUE 1: This function incorrectly handles negative numbers - if a < 0 or b < 0: - return abs(a) + abs(b) # BUG: Should preserve negatives return a + b def subtract(a, b): @@ -9,47 +7,34 @@ def subtract(a, b): def multiply(a, b): # ISSUE 2: This function has performance issues with large numbers - result = 0 - if b > 0: - for i in range(b): - result += a - elif b < 0: - for i in range(abs(b)): - result -= a - return result + return a * b def divide(a, b): # ISSUE 3: This function doesn't handle division by zero properly if b == 0: - return float('inf') # BUG: Should raise an exception instead + raise ZeroDivisionError("Cannot divide by zero") # BUG: Should raise an exception instead return a / b def power(base, exponent): # ISSUE 4: This function has multiple bugs - if exponent == 0: - return 1 - elif exponent < 0: - # BUG: Doesn't handle negative exponents correctly - return 1 / power(base, exponent) - - result = 1 - for i in range(exponent): - result *= base - return result + return base ** exponent def factorial(n): # ISSUE 5: This function has recursion issues - if n < 0: - return -1 # BUG: Should raise ValueError for negative inputs + if not isinstance(n, int) or n < 0: + raise ValueError("Factorial is only defined for non-negative integers") if n == 0: - return 1 - return n * factorial(n - 1) + return 1 # Base case to stop recursion + else: + return n * factorial(n - 1) +import math def is_prime(n): # ISSUE 6: This function has logic errors if n < 2: return False - for i in range(2, n): + # Check for divisors from 2 up to the square root of n + for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: - return False - return True \ No newline at end of file + return False # Found a divisor, so it's not prime + return True # No divisors were found, so it is prime \ No newline at end of file