public int ugly(int x, int y) {
if(x<0)
return x;
else
return ugly(x - 1,y * 2) - x;
}
What is returned by ugly(4,2)... im not sure wat u do with this part ugly(x - 1,y * 2) - x.... could someone plz explain how u solve this? thank u
2006-12-01
16:36:47
·
5 answers
·
asked by
jbljackie
2
in
Computers & Internet
➔ Programming & Design
this is not a school assignment... i do not even have computer science as a class... i am just studying so do not think i am cheating.
2006-12-01
16:45:38 ·
update #1
This is recursion. Your question asks 'how' to solve it, not what the answer is, so I dont think it's cheating either.
The way to solve it is to put your example numbers in there and walk through the logic.
The first time through, x (4) is not <0 so you must call the procedure again using x-1 (4 -1), getting its answer and then subtracting the original x (4) from that.
The next time through, x (3) is not <0 so you must call the procedure again using x-1 (3 -1), getting its answer and then subtracting x (3) from that.
The next time through, x (2) is not <0 so you must call the procedure again using x-1 (2 -1), getting its answer and then subtracting x (2) from that.
Repeat this process until the condition is true. It's at this point you can begin to backtrack through all your calls and do the math.
Make it easy on yourself and start with ugly(-1,0). Then try starting with ugly(0,0). Then ugly(1,0) You should start to notice a pattern. (You should also notice that the y value in this procedure is irrelevant.) Once you have the practice with those first few, you should find it easy to go 3 more and solve it.
2006-12-01 17:08:16
·
answer #1
·
answered by Cribbage 5
·
1⤊
0⤋
The 'ugly' function is recursive...so let's start with your 4,2 inputs and trace it...
ugly(4,2)
x < 0 : false
return ugly(3,4)-4
x<0 : false
return ugly(2,16)-3
x<0 : false
return ugly(1,256)-2
x<0 : false
return ugly(0,65536)-1
x<0 : false
return ugly(-1,4294967296)-0
x<0 : true
return -1
return -1 - 0 = -1
return -1 - 1 = -2
return -2 - 2 = -4
return -4 - 3 = -7
return -7 - 4 = -11
ugly(4,2) = -11
2006-12-01 17:23:26
·
answer #2
·
answered by W C 1
·
2⤊
0⤋
Easy answer, do the iterations:
Iteration 1 (4,2)
x>0
ugly(3,4)-4;
iteration 2 (3,4)
x>0
ugly(2,8)-3
iteration 3 (2,8)
x>0
ugly(1,16)-2
iteration 4 (1,16)
x>0
ugly(0,32)-1
iteration 5 (0,32)
x=0
ugly(-1,64)-0
iteration 6 (-1,64)
x<0, return (-1)
return iteration 5
return -1-0 (-1)
return iteration 4
return -1-1 (-2)
return iteration 3
return -2-2 (-4)
return iteration 2
return -4-3 (-7)
return iteration 1
return -7-4 (-11)
ugly(4,2) = -11
2006-12-01 18:04:48
·
answer #3
·
answered by Anonymous
·
0⤊
0⤋
this one seems like a school test or assignment. No one should help you. All i can say is that this is called recursion. Do a google and that might help...
2006-12-01 16:43:22
·
answer #4
·
answered by anyone 2
·
0⤊
0⤋