Why doesn't this loop terminate?

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-03-24T03:11:34Z Indexed on 2010/03/24 3:23 UTC
Read the original article Hit count: 297

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about regression

Related posts about collatz