gistlib
Here is a simple Python function that performs division using only subtraction:
main.pydef division(dividend, divisor): # Handle division by zero if divisor == 0: raise ZeroDivisionError('division by zero') quotient = 0 sign = 1 # Determine the sign of the quotient if dividend < 0: dividend = -dividend sign = -sign if divisor < 0: divisor = -divisor sign = -sign # Perform repeated subtraction while dividend >= divisor: dividend -= divisor quotient += 1 # Apply the sign quotient *= sign return quotient 530 chars27 lines
def division(dividend, divisor): # Handle division by zero if divisor == 0: raise ZeroDivisionError('division by zero') quotient = 0 sign = 1 # Determine the sign of the quotient if dividend < 0: dividend = -dividend sign = -sign if divisor < 0: divisor = -divisor sign = -sign # Perform repeated subtraction while dividend >= divisor: dividend -= divisor quotient += 1 # Apply the sign quotient *= sign return quotient
To use this function, simply call it with a dividend and a divisor:
main.py>>> division(10, 2) 5 >>> division(5, 2) 2 >>> division(-5, 2) -2 >>> division(10, 0) ZeroDivisionError: division by zero 122 chars9 lines
>>> division(10, 2) 5 >>> division(5, 2) 2 >>> division(-5, 2) -2 >>> division(10, 0) ZeroDivisionError: division by zero
gistlibby LogSnag