Project Euler Problem 14 Solution – Longest Collatz sequence

Longest Collatz sequence is a very cool problem which I first encountered (requiring different things, but method was the same) when I started learning C++. The problem states that for any set of positive integers you do the following:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

and that eventually, any number will end up at 1. the problem requires us to count how many numbers are in the chain between n and 1… the solution to this classic project Euler problem is below in Java.

 

/*
 * Author: Gal Appelbaum
 * www.galappelbaum.com
 */

public class p14 {

    public static void main(String[] args){
        int longestChain = 0;
        int finalNumber = 0;
        int count = 1;
        double currentNumber = 0;
        for(int i = 2; i < 1000000; i++){
            currentNumber = i;
            while(currentNumber != 1){
                if(currentNumber % 2 == 0)
                    currentNumber = currentNumber/2;
                else
                    currentNumber = 3*currentNumber + 1;
                count++;
            }
            if(count > longestChain){
                longestChain = count;
                finalNumber = i;
            }
            count = 0;
            System.out.println(i);
        }
        System.out.println(finalNumber);
    }
}

									

Leave a Reply

Your email address will not be published. Required fields are marked *