Moca
Moca

Reputation: 53

Division returning quotient and remainder using a loop and subtraction?

I'm doing exam practice, and one of the questions asks you to create a function called divide(a,b) calculates both the quotient and remainder of the two parameters and returns both results. You cannot use the built in division operator or modulo operator and have to do it using a loop which repeatedly calls the subtract function (a function made in previous step of activity. I've essentially figured out how to determine the quotient and remainder, but I can't figure out how to do the division in a loop using subtraction only addition. This is the code I have so far (note: the input for a/b is done separately, this is just the functions):

def add(a,b):
    return(a + b)

def subtract(a,b):
    return(a - b)

def divide(a,b):
    c = 0
    d = 0
    while add(d, b) <= a:
        c = add(c, 1)
        d = add(d, b)

    sub = multiply(b,c)    
    rem = subtract(a,sub)

    return(c,rem)

tl;dr how can alter my while loop in divide(a,b) to use subtraction instead of division?

Upvotes: 0

Views: 3525

Answers (1)

Hallsville3
Hallsville3

Reputation: 511

Okay, so the key here is to recognize that the quotient is how many times you can evenly subtract your divisor, while the remainder is what’s left. So:

def divide(a, b):
    quotient = 0
    while a>b:
        quotient = add(quotient, 1)
        a = subtract(a,b)
    return (quotient, a)

Upvotes: 2

Related Questions