Based on the Collatz Conjecture, all values of n will eventually reach the value of 1 and fall into the pattern of 1, 4, 2, 1, 4... continuing forever. Therefore we want to have a base condition to detect when the input value is equal to 1. The code that checks for this is:
if(n == 1)
return 0;
The next step to check is if the value that has been input is even or odd (n % 2 == 0 will return true if n is even and false if n is odd).
If the value is even, based on the Collatz Conjecture, we divide by two. This is completed by the code:
else if(n % 2 == 0)
return 1 + collatz(n / 2);
This is basically saying, "If the number is even, take a step by dividing by 2 and calculate the number of steps it takes for that number."
If the value is odd (not even, hence the else), the Collatz Conjecture tells us to multiply by 3 and add 1. The code for this is:
else
return 1 + collatz(3 * n + 1);
The interpretation of this is, "If the number is odd, take a step by multiplying by 3 and adding 1 and calculate the number of steps for the resulting number."
The 1 + collatz(...)
is taking the step you just took, represented by the 1, and then adding the number of steps (calculated recursively) that the resulting number will take.
For example, collatz(5)
will result in the recursive method returning 1 + collatz(16) + collatz(8) + collatz(4) + collatz(2) + collatz(1)
or,
1 + 1 + 1 + 1 + 1 + 0 = 5
This tells you that it takes 5 steps to complete the Collatz Conjecture for the value 5.