Longest Collatz Sequence

Alpan Karaca picture Alpan Karaca · Nov 1, 2012 · Viewed 10.6k times · Source

While doing my Java homework which is to implement the Collatz Conjecture, I thought of a different objective which is to find the longest Collatz sequence. My program counts the steps as follows:

public class Collatz {

static int count = 0;

    static void bilgi (int n){

        int result = n;
        System.out.println("Result: "+result+ " Step: "+count);

        if (result <= 1) {
            result = 1;
        } else if (result%2 == 0){
            result = result/2;
            count = count + 1;
            bilgi(result);

        } else {
            result = (result*3)+1;
            count = count + 1;
            bilgi(result);
        }
    }

    public static void main(String[] args) {
        bilgi(27);
    }

}

I want to find the highest step count.

Answer

Vesper picture Vesper · Nov 2, 2012
static int bilgi(int n) {
    int result = n;
    if (result <= 1) return 1;
    if (result % 2 == 0) return 1+bilgi(result/2);
    return 1+bilgi(3*result+1);
}

Then you collect the results of bilgi(i) calls and select maximal.