cs help

Reply

Join Date: Jun 2008
Posts: 3
Reputation: jhartley3 is an unknown quantity at this point 
Solved Threads: 0
jhartley3 jhartley3 is offline Offline
Newbie Poster

cs help

 
0
  #1
Jun 7th, 2008
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..
Last edited by jhartley3; Jun 7th, 2008 at 5:23 pm.
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 1,008
Reputation: woooee is a jewel in the rough woooee is a jewel in the rough woooee is a jewel in the rough 
Solved Threads: 285
woooee woooee is offline Offline
Veteran Poster

Re: cs help

 
0
  #2
Jun 7th, 2008
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.
  1. def divide(dividend, divisor):
  2. n = dividend - divisor
  3. print "n =", n
  4. while n > 0:
  5. print "entering while statement"
  6. return
Last edited by woooee; Jun 7th, 2008 at 9:39 pm.
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 122
Reputation: slate is an unknown quantity at this point 
Solved Threads: 30
slate slate is offline Offline
Junior Poster

Re: cs help

 
1
  #3
Jun 8th, 2008
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:
  1. def divide(dividend, divisor):
  2. counter=0
  3. n=dividend-divisor
  4. while n>0:
  5. n-=divisor
  6. counter+=1
  7. 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.
Last edited by slate; Jun 8th, 2008 at 10:55 am.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC