Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Recursion question

800147Apr 8 2011 — edited Apr 10 2011
Hi,
public static int mystery(int a, int b) {
		   if (b == 0)     
			   return 0;
		   if (b % 2 == 0) 
			   return mystery(a+a, b/2);
		   else{
			   return mystery(a+a, b/2) + a;
		   }
		}
Can someone, please help me understand why the above code calculates a*b ? I tried with pen and paper - don't get it, tried with debugger - same result. Tried with System.out.println(mystery(a,b)); just before every return statement in effort to enlighten the case and I got StackOverflowError.

Thanks in advance.


Edit: I got it why the stack overflows when I recursively call the method through System.out.println();

Edited by: blias on Apr 8, 2011 6:14 PM
This post has been answered by walterln on Apr 9 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 8 2011
Added on Apr 8 2011
24 comments
1,063 views