Java function does not return the correct value

Asked

Viewed 24 times

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;
    }
}

1 answer

1


From what I understand the function is being called recursively and the return of the last call is being ignored in the previous call (note that you are calling the function within itself as if it were returning void, that is, nothing happens with the value that is returned, you are doing nothing with the value that comes back to itself).

I don’t know how the algorithm should be, but it has to be changed. It’s probably just a matter of adding return before each call.

If this reasoning is right then it would look something like this:

public static int algorithm(int n, int cycleLength)
{
    cycleLength++;
    
    if(n == 1) {
        return cycleLength;
    }

    if(n % 2 == 1) {
        return algorithm(3 * n + 1, cycleLength);
    } else {
        return algorithm(n / 2, cycleLength);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.