import java.util.ArrayList;
import java.util.Scanner;

/**
 * Outputs the hailstone sequence starting at a positive integer chosen by the user. Each
 * term of sequence is obtained from the previous term according to the following rule:
 * 
 *    If even, divide by 2.
 *    If odd, multiply by 3 and add 1. 
 * 
 * The sequence terminates when the number 1 appears. 
 * 
 * Example: 3 10 5 16 8 4 2 1. 
 * 
 * Aside: it is a famous conjecture in mathematics that every hailstone sequence 
 * eventually terminates, but nobody has ever been able to prove that this is so. 
 *
 * @author Drue Coles
 */
public class HailstoneSequences {

    public static void main(String[] args) {
        
        System.out.print("Enter a positive integer: ");
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        ArrayList<Integer> hailstones = getSequence(n);
        int size = hailstones.size();

        String s = "The hailstone sequence starting at %d has %d terms.%n%n";
        System.out.printf(s, n, size);

        // Output contents of the list in columns of size 5 with 10 numbers per line.       
        int count = 0; // count of numbers on current line
        for (int num : hailstones) {
            System.out.printf("%5d ", num);
            if (++count % 10 == 0) {
                System.out.println();
            }
        }
        System.out.println();
    }

    /**
     * Returns a list of numbers in the hailstone sequence starting at n.
     */
    private static ArrayList<Integer> getSequence(int n) {
        ArrayList<Integer> hailstones = new ArrayList<>();
        hailstones.add(n);
        while (n > 1) {
            if (n % 2 == 0) {
                n /= 2;
            } else {
                n = 3 * n + 1;
            }
            hailstones.add(n);
        }
        return hailstones;
    }
}