def divide(dividend, divisor):

This function should return the calculated value of integer division of divisor by dividend. Calculate the solution by using subtraction recursively to divide the two numbers. You are not allowed to use the division operator for this problem. Explanation: note that 7 divided by 2 is 3 because you can subtract like so: 7 – 2 = 5. 5 – 2 = 3. 3 – 2 = 1. 1 – 2 = -1 (so stop.) We were able to subtract 2 from our original 7 three times before reaching a negative number.

So far i have:
def divide(dividend, divisor):
n = dividend - divisor
while n > 0:
return

i know this must be easy im just not seeing it..

3
Contributors
2
Replies
4
Views
10 Years
Discussion Span
Last Post by slate

Add some print statements. And I've formated your snippet with code statements in the way that I think it would have to be indented, but there is no way to tell.

``````def divide(dividend, divisor):
n = dividend - divisor
print "n =", n
while n > 0:
print "entering while statement"
return``````

Well.
There are two kind of problems in the snippet. Is the algorithm good (gives the right result in a reasonable time), the other is if the program implements this algorithm.

The algo would be in some pseudo language:
input: dividend, divisor nonnegativ integers
counter=0
n=dividend-divisor
while n>0
do
n=n-divisor
counter=counter+1
doend
return counter

In python that would be:

``````def divide(dividend, divisor):
counter=0
n=dividend-divisor
while n>0:
n-=divisor
counter+=1
return counter``````

This gives back how many times the divisor is in dividend. If you want to have the remainder, than you should return n+divisor.

If you don't make this program for learning purposes, you may have a look at the divmod built in function, which does the same thing, and more.