rifle123
rifle123

Reputation: 259

java collatz code not stop when reach 1

I created this collatz code, when I run the command 'java collatz 7', my program doesn't terminate when n reaches 1, instead it keeps repeating the sequence until the StackOverflowError. Could anyone point out what is the issue here? Thx

public class collatz{
    public static void collatz(int n){
            System.out.println(n+" ");
            if(n==1)
                    return;
            if(n%2==0)
                    collatz(n/2);
            collatz(n*3+1);
    }
    public static void main(String[] args){
            collatz(Integer.parseInt(args[0]));
    }
}

Upvotes: 0

Views: 92

Answers (1)

D M
D M

Reputation: 1410

This looks like the problem:

        if(n%2==0)
            collatz(n/2);
        collatz(n*3+1);

If n%2==0 it will call BOTH of those. I think it should instead be this:

        if(n%2==0)
            collatz(n/2);
        else
            collatz(n*3+1);

Now it will only call it once.

Upvotes: 1

Related Questions