/******************************************************************************
 * Name: Donna Gabai
 * NetID: dgabai
 * Precept: P99
 * 
 * Fall 2014, Programming Exam 1, Collatz Conjecture:
 * This program finds the length of a Collatz sequence given N.
 * 
 * Dependencies: StdOut.java
 ****************************************************************************/

public class F14Part1 {
 
    // returns the length of the Collatz sequence of the argument N
    public static int seqLength(int N) {
        int length = 1;
        int n = N;
        
        // count how many times you can compute collatz numbers until you hit 1
        while (n != 1) {
            
            // compute the next collatz number
            if (n % 2 == 0) n = n/2;
            else n = 3*n + 1;
            length++;
        }
        
        return length;
    }
    
    // the recursive collatz function, unedited
    public static void collatz(int N) {
        StdOut.print(N + " ");
        if (N == 1) return;
        if (N % 2 == 0) collatz(N/2);
        else collatz(3*N + 1);
    }
    
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        
        // find the length of the collatz sequence for N
        int length = seqLength(N);
        
        // print sequence if length < 20
        if (length < 20) collatz(N);
        
        // print length of sequence in square brackets
        StdOut.println("[" + length + "]");
    }
}