Python integer division with remainder

Refer to the following post for more details. This post is only Python implementation

Python code

#  Integer division calculator
def Division(numerator, denominator):

	# Divide by zero special case
	if denominator == 0:
		return [-999, -999]

	# Both are equal special case
	if numerator == denominator:
		return [1, 0]
	
	quotient = 0

	# Get the sign of the division
	sign = 1

	if numerator * denominator < 0:
		sign = -1
	
	# Convert to positive or you can use
	# built in ABS function
	if numerator < 0:
		numerator = -1 * numerator

	if denominator < 0:
		denominator = -1 * denominator

	while numerator > denominator:
		quotient = quotient + 1
		numerator = numerator - denominator
	
	return [sign * quotient, numerator]

# Give it a try
result = Division(9, 2)
print "9/2 = {} and remainder = {}".format(result[0], result[1])

Thanks for reading, for questions or feedback please use the comments section below.

Tags:

Leave a Reply