user1197252
user1197252

Reputation:

Project Euler 14 - Java StackOverflowError

For those unfamiliar with the problem, here it is.

I am getting a StackOverflowError with the following code:

public class LongestCollatzSequence {

static int count = 1;

public static void main(String[] args) {
    final int range = 1000000;
    int maxSeq = 0;
    List<Integer> chainList = new ArrayList<Integer>();

    for(int i = 1; i <= range; i++) {
        generateSequence(i);
        if(chainList.isEmpty()) {
            chainList.add(count);
            count = 1;
        } else if(!chainList.contains(count) && count > Collections.max(chainList)) {
            chainList.clear();
            chainList.add(count);
            maxSeq = i;
            count = 1;
        } 
    }
    System.out.println("Sequence starting number: "+maxSeq);
}

private static void generateSequence(int num) {
    if(num == 1) {
        return;
    }
    if(num % 2 == 0) {
        count++;
        generateSequence(num/2);
    } else {
        count++;
        generateSequence(num*3+1);
    }
}

}

High level flow:

-For numbers 2 - 100000, generate a collatz sequence for that number. -Chain list is a list to store the length of the sequence generated for each number i.e. sequence size for number 13 is 10 (see example). -If the current sequence size is bigger than the max in the chain list, clear chain list and add the new max, also store the value of i in maxReq to remember the starting number that produces the longest chain.

Upvotes: 0

Views: 308

Answers (1)

venergiac
venergiac

Reputation: 7717

Interesting problem but the int in java is limited to 2^31-1 you could crox this limit use long or BigInteger

  private static void generateSequence(long num) {
    if (num == 1) {
        return;
    }
    if (num % 2 == 0) {
        count++;
        generateSequence(num / 2);
    } else {
        count++;
        generateSequence(num * 3 + 1);
    }
}

Upvotes: 2

Related Questions