algorithm - Java recursion provides two different results. Why? -


i have ambiguous understanding result of following code segment. please me understand example.

this first code segment:

public static void main(string args[]) {     int number = 4;     system.out.print(what(number)); }  public static int what(int number){     if(number < 2)         return 1;     else         return what(number-2) + what(number -1); } 

this returns 5 result. when trying run recursion method individually operand both code segments return 1 result.

the following code returns 1 result:

public static int what(int number){     if(number < 2)         return 1;     else         return what(number-2); } 

and same holds code:

public static int what(int number){     if(number < 2)         return 1;     else         return what(number-1); } 

i need understand how works.

the first method sums 1's, whereas latter method print result of what(), can nothing more or nothing less 1.

example of first method:

what(4) = what(2) + what(3) = what(0) + what(1) + what(1) + what(2) = 1 + 1 + 1 + what(0) + what(1) = 3 + 1 + 1 = 5

or, if better visualization:

                   what(4)                   /  +   \                  /        \                      what(2)      what(3)             /   \         /     \        what(0) what(1) what(1) what(2)          =1     =1       =1     /  \                             what(0) what(1)                               =1      =1 

example of second method:

what(4) = what(2) = what(0) = 1

                     what(4)                        |                      what(2)                        |                      what(0)                        =1 

example of final method:

what(4) = what(3) = what(2) = what(1) = 1

                     what(4)                        |                      what(3)                        |                      what(2)                        |                      what(1)                        =1 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -