Search code examples
algorithmnumberssequencecollatzhighest

Longest Collatz Sequence


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.


Solution

  • 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.