Ask your own question, for FREE!
Mathematics 6 Online
OpenStudy (anonymous):

What does the method return: mystery(4,3) public static int mystery(int x, int y){ if(y==1) return x; else return x*mystery(x, y-1); } I watched some videos and read some tutorials online about recursions and I believe I understand, but what I don't understand is x*mystery(x,y-1) What does that line of code even do? How do I times 4 by (4,2)?

OpenStudy (anonymous):

mystery(4,3) returns 4*mystery(4,2). mystery(4,2) returns 4*mystery(4,1). mystery(4,1) returns 4. Therefore, mystery(4,3) = 4 * 4 * 4 = 64. You should ask this in the computer science section.

OpenStudy (anonymous):

By the way, this is just a recursive version of the power function.

OpenStudy (anonymous):

Wait, how did you get that? What does 4*mystery(4,2) do?

OpenStudy (anonymous):

Can you write it step by step please? I'm pretty new to it

OpenStudy (anonymous):

A recursive function is a function that calls itself and has the following basic structure: 1. A base case 2. A recursive case The base case ensures that the recursive procedure terminates and the recursive case ensures that it keeps moving.

OpenStudy (anonymous):

In this case, the base case is y == 1. This means that as soon as the y argument gets passed a value of 1, the procedure will terminate. The recursive case is x * mystery(x, y - 1). Notice how it modified the rightmost argument; if this is not done, then the recursion will hit an infinite loop and you'll get a stack overflow error.

OpenStudy (anonymous):

In the last one, mystery(4,1) returns 4. Why doesn't it return 4,0?

OpenStudy (anonymous):

WAIT! Oh I get it now!

OpenStudy (anonymous):

Thanks!

OpenStudy (anonymous):

To see why it doesn't return mystery(4, 0), look at the base case. Recursion is often a natural way to implement solutions for certain kinds of problems, but it is rather slow and inefficient, in my opinion. An iterative version of your mystery function would look something like this: int mystery(int x, int y) { int n = x; for (int i = 1; i < y; i++) n *= x; return n; }

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!