I have tried but failed to do so. Could I have a push in the right direction?
+5
A:
Pseudocode only, since it's probably homework:
def div(a,b):
if a < b return 0
return div(a-b,b) + 1
Will only work for positive numbers, fixing it for negatives and divide-by-zero is left as an exercise.
It works by repeatedly subtracting b
from a
, and going down a level, until you can no longer subtract b
from a
without going negative. Then it returns up the recursion tree, adding 1 for each level you went down.
Some hints for handling signs and errors:
- Detect straight up if b is equal to zero and exit with an error.
-a/-b
is the same asa/b
.-a/b
is the same as-(a/b)
.a/-b
is also the same as-(a/b)
.- those four special cases can be handled when first entering the
div
function, the final three can also be done by just adding someif
statements and one recursion level.
paxdiablo
2009-11-24 06:07:11
"fixing it for negatives and divide-by-zero is left as an exercise" :nice one. :)
chong
2009-11-24 06:30:05
A:
#include <stdio.h>
int div(int a, int b){
int c;
c=a-b;
if(c<=0){
return 1;
}else{
return div(c, b) + 1;
}
}
int main(void){
printf("%d", div(12, 4));
return 0;
}
This works
http://codepad.org/iWhmbUua
Logan
2009-11-24 06:10:28
@Logan, it's considered bad form to give code for homework since (1) it's cheating; (2) it won't help since the OPs educators can see here as well; and (3) it doesn't help people develop analytical skills. No downvote since you're new here but it's something you may want to keep in mind for future.
paxdiablo
2009-11-24 06:14:57
Chances are the homework spec wants div(12, 5) to return 2, as 12/5 would. So, you should change it to "if (c<0) return 0;", which will yield the expected behavior.
Dathan
2009-11-24 06:15:34