Home > DeveloperSection > Forums > Understanding recursive method. Help!
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    April-29-2015 12:34 AM

 Java Java 
Ratings:


 1 Reply(s)
 398  View(s)
Rate this:
This code is  working(it's purpose is to return the product of n odd numbers). My problem is, I do not understand how exactly works. What goes after what, how exactly the values are caluclated and multiplied and what happens in the return after n==1. 
Sorry if I am asking for too much, but can someone explain this to me in detail? 
public static int multiplyOdds (int n) {
        System.out.println(n);
        if(n==1){
        return 1;
         
        }else return  multiplyOdds(n-1) * (n*2-1);
         
         
    }


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    April-29-2015 7:16 AM

well, there is not so much to explain. Just write out in ful what happens
when you issue 'multiplyOdds(3)'.

When n = 3 we get
(since 3 != 1):
(2 * 3 - 1) * multiplyOdds(2) = 5 * multiplyOdds(2) =
(since 2 != 1):
5 * (2 * 2 - 1) * multiplyOdds(1) = 5 * 3 * multiplyOdds(1) =
(since n == 1):
5 * 3 * 1
= 15


Don't want to miss updates? Please click the below button!

Follow MindStick