Reputation: 259
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
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