Search code examples
javaarrayscollatz

Finding the Collatz sequence with the highest amount of terms


I'm currently working on a problem about the Collatz conjecture. I shall attach an image of the problem.

Question (from ProjectEuler)

Now the problem obviously states between 1 and 1,000,000. But I've added a bit of functionality by allowing the user to pick where the starting and ending point should be. Though I've ran into a problem. (As a first year CS student with no prior programming experience, my knowledge is very limited at the moment).

My idea on how to find the one with the highest sequence, or highest 'loopCount' is to push the number with its corresponding loop count into an array, and try to find the maximum loop count value in that array. But as far as I'm concerned, that would involve a 2d array.

As I said, my programming skills are limited (we haven't covered arrays yet), so I don't know how to go about starting this.

Here's what I have so far:

    System.out.println("Enter starting point:");
    Scanner userStartingPoint = new Scanner(System.in);
    long startingPoint = userStartingPoint.nextInt();

    System.out.println("Enter ending point:");
    Scanner userEndingPoint = new Scanner(System.in);
    long endingPoint = userEndingPoint.nextInt();

    long timeBefore = System.currentTimeMillis();
    int loopCount;

    for(long i = startingPoint; i <= endingPoint; i++) {

        long number = i;
        loopCount = 1;

        while(number != 1) {
            if(number%2 == 0) {
                number = number/2;
            } else if(number%2 != 0) {
                number = (3*number)+1;
            }
            loopCount++;
        }

        System.out.println("Number: " + i + ". " + "Loop count: " + loopCount + ".");
    }

    long timeAfter = System.currentTimeMillis();
    long timeTaken = timeAfter - timeBefore;
    System.out.println(endingPoint - startingPoint + " sequences.");
    System.out.println("Time taken: " + timeTaken/1000 + " seconds.");

I use 'long' as a data type for a lot of variables here because I've found that some numbers have iterations that go above the amount that the 'int' data type can handle.


Solution

  • Just save the highest loopCount in an extra variable and update it after each iteration if it increased.

    int maxCount = 0;
    int loopCount;
    
    for(long i = startingPoint; i <= endingPoint; i++) {
    
        long number = i;
        loopCount = 1;
    
        while(number != 1) {
            if(number%2 == 0) {
                number = number/2;
            } else if(number%2 != 0) {
                number = (3*number)+1;
            }
            loopCount++;
        }
        if(loopCount > maxCount){
            maxCount = loopCount;
        }
        System.out.println("Number: " + i + ". " + "Loop count: " + loopCount + ".");
    }
    System.out.println("Highest loopCount : " + maxCount);