Question

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.

Was it helpful?

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.

OTHER TIPS

The longest progression for any initial starting number less than 100 million is 63,728,127, which has 949 steps. For starting numbers less than 1 billion it is 670,617,279, with 986 steps, and for numbers less than 10 billion it is 9,780,657,630, with 1132 steps

source: http://en.wikipedia.org/wiki/Collatz_conjecture

If you're looking for max between 1 and 100 you could replace:

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

with :

public static void main(String[] args) {

    static int maxcountsofar = 0;
    static int start = 0;
    static int thisone = 0;
    for (int iloop = 1; iloop <= 100; iloop++)
    {
       thisone = bilgi(iloop);
       if (thisone > maxcountsofar)//if this one is bigger than the highest count so far then
      {
        start = iloop;//save this information as best so far
        maxcountsofar = thisone;
      }
    }
    System.out.println("Result: " + start.Tostring() + " Step: " + maxcountsofar.Tostring() );
    //I know this is a really old post but it looked like fun.

}

/* also, take the println() out of the bilgi() function, it would generate a line for each step encountered which would be worthless and extremely time consuming.

Use Vesper's bigli() because it's much faster than yours. */

I know this is an old question, but I was just solving it and I would suggest for anyone doing this, just using an arraylist and getting the .size(), I did it that way, because I wanted to see the values as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top