Search code examples
javarecursioncollatz

Project Euler 14 Java


I have been having trouble on Problem 14 on Project Euler. I don't understand why my code(Java) isn't working and any help would be appreciated.

public class Calculate {

    public static void main(String[] args){
        System.out.println(calc());
    }

    public static int calc(){
        int max = 0;
        int maxI = 0;
        for (int i = 0; i < 1000000; i++){
            if (seqLen(i) >= max){
                max = seqLen(i);
                maxI = i;
            }
        }
        return maxI;
    }

    public static int seqLen(int seed){
        if (seed <= 0) return 0;
        if (seed == 1) return 1;
        int len = 1;
        if (seed % 2 == 0){
            len += seqLen(seed/2);
        }
        else{
            len += seqLen((3*seed)+1);
        }
        return len;
    }

}

Thanks!


Solution

  • You run into an overflow with your int variables.

    The maximum number appearing in this computation (when using a brute force approach) is 56991483520.

    Java's int maximum value is 2^31-1 == 2147483647, which is obviously smaller.

    So change your variables etc to use long. Here the max value is 2^63-1 == 9223372036854775807, which will be fitting for all values.