Pythagoras
Pythagoras

Reputation: 1

Division as repeated subtraction based on another function?

How can I use the "subtraction()" function into the division() function in a for/while loop to make a division operation based on repeated subtractions, giving the quotient as well as the remainder? Thank you. Here is my code so far:

def subtraction(x, y): #subtraction function
    return x - y

def division(x, y): #division function
    repeatsub = 0
    for i in range(y):
        repeat = subtraction(repeatsub, 2)
    return repeatsub

Upvotes: 0

Views: 643

Answers (3)

solid.py
solid.py

Reputation: 2812

This performs integer division and returns the quotient and the remainder.

def subtraction(x, y): # Subtraction function
    return x - y

def division(x, y): # Division function
    if y == 0:
        raise ZeroDivisionError
    quotient = 0
    remainder = x
    while remainder >= y:
        remainder = subtraction(remainder, y) # or remainder -= y
        quotient += 1
    return (quotient, remainder)

print("Quotient and remainder are", division(10, 2))

Output:

Quotient and remainder are (5, 0)

Upvotes: 0

Or b
Or b

Reputation: 816

The simplest way I find to do it is according to this guide which substracts x from y until 0 is reached.

Try this code:

def subtraction(x, y): #subtraction function
    return x - y

def division(x, y): #division function
    if (y==0):
        return -1 #ZeroDivisionError
    repeatsub = 0
    while (x>y):
        x = subtraction(x, y)
        repeatsub +=1
    return repeatsub

which for this main script:

x=13
y=2
print(division(x,y))

prints 6 as expected.

I also suggest to take care of the special case of division by zero, where in this example I return -1 but you can change use any other solution that fits you.

The while condition x>y makes sure we still need to substract, if you are sure that it is an integer division you can change it to x>0

Note: My solution also works when y is greater than x which makes it elegant and simple.

Upvotes: 0

g_bor
g_bor

Reputation: 1092

Division is writing a number into the form: x=ay+b where b<y. So you should repeatedly subtract y from x, while the result>=y. The final result is the remainder. The quotient is the number of calls made, you can do it like quotient=0 and quotient=quotient+1 after each subtraction.

Upvotes: 1

Related Questions