public class Collatz {

    public static void main(String[] args) {
        final int MAX = 65536;
        int loop;
        int maxiters=0;
        int maxx=0;

        // loop from 1 to MAX
        for (loop=1;loop<=MAX;loop++) {
            long x,newx; // ints are ok but use of long avoids overflow if MAX > 2^16
            int iterations = 0;

            // we start off with the loop index as x
            x = loop;

            // compute iterated f(x) until we reach the cycle
            while (x!=1) {
                // compute f(x)
                if (x%2==0) {
                    // x is even
                    newx = x/2;
                } else {
                    // x is odd
                    newx = 3 * x + 1;
                }
                iterations++;
                // set output to new input
                x = newx;
            }

            // keep track of the number generating the largest number of iterations
            if (iterations>maxiters) {
                maxiters=iterations;
                maxx = loop;
            }
        }

        // Output result
        System.out.println("Max iterations of f was "+maxiters+" by the number "+maxx);
    }
}
