Back | Reverse | Quick Reply | Post Reply |

java challenge (or not)
Link | by floopy! on 2006-10-21 17:58:30 (edited 2006-10-22 10:04:55)
ahhhh myst(b-2, a-1) <---<< should it not be myst (a-1, b-2)???
and what is a StackOverflowError?
so confusing =_=
public static int myst(int a, int b)
{
  if(b==1)
     return a;
  else 
     return a + myst(b-2, a-1);
}

What is the value of myst(6,4)?

What is the value of myst(3,5)?

Re: java challenge (or not)
Link | by psoplayer on 2006-10-22 10:05:36
Ooh, recrusion! Fun stuff. Give me a bit to mull this one over.


Re: java challenge (or not)
Link | by floopy! on 2006-10-22 10:43:14
^^'''''' be my guest... this is confusing for me u know?

Re: java challenge (or not)
Link | by Sheep on 2006-10-22 10:52:27
myst(6,4) should return 11.

myst(3,5) will never return a value, hence the overflow, because b will never be = 1.
Already in the 3de step of the recursion it goes negative and continues that way, till it eventually overflows.

[Quiet dogs know when to be silent]
Sheep & Tiojar's Anime Episodes

Re: java challenge (or not)
Link | by psoplayer on 2006-10-22 11:00:28
Well, with the code as you typed it, myst(6,4) would return 11.
I'm also assuming that your StackOverflowError comes up when you try myst(3,5)?
Well, here's what it's doing:

It keeps swaping the values, subtracting 2 from B and 1 from A, until B exactly equals 1, and then it returns the sum of all the values that A had been. If B never exactly equals 1, as would be the case with myst(3,5), it will just go on forever and never return any value.
If you changed it to myst(a-1, b-2) then it would do the same thing, except for the switching places part.


Re: java challenge (or not)
Link | by floopy! on 2006-10-22 17:23:21
woooow thank you so much =)
i'm really glad that both of u answered so clearly! also, that graph helped me fully understand the process. there's nothing like figuring out something on a program and seeing it work and second to that is comprehending after someone explains it to u XD

Back | Reverse | Quick Reply | Post Reply |

Copyright 2000-2024 Gendou | Terms of Use | Page loaded in 0.0136 seconds at 2024-12-28 05:22:07