0
I’m not getting the desired value from the recursive function below. I have tried putting a System.out.println to monitor the values of the cycleLength and n variables and the result was that for the tested value(22) the output would be 16 and n would end with the value 1 really. Hence, I cannot understand why the function keeps returning -1. For me the Return -1 would never be reached.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(algorithm(2, 0));
input.close();
}
public static int algorithm(int n, int cycleLength) {
cycleLength++;
if(n == 1) {
return cycleLength;
}
if(n % 2 == 1) {
algorithm(3 * n + 1, cycleLength);
}
else {
algorithm(n / 2, cycleLength);
}
return -1;
}
}