Why doesn't this loop terminate?
- by David
Here's the sample code:
public static void col (int n)
{
if (n % 2 == 0)
n = n/2 ;
if (n % 2 != 0)
n = ((n*3)+1) ;
System.out.println (n) ;
if (n != 1)
col (n) ;
}
this works just fine until it gets down to 2. then it outputs 2 4 2 4 2 4 2 4 2 4 infinitely. it seems to me that if 2 is entered as n then (n % 2 == 0) is true 2 will be divided by 2 to yeild 1. then 1 will be printed and since (n != 1) is false the loop will terminate.
Why doesn't this happen?