Java Implementation of Problem 14

View source code here on GitHub!

public class p0014 implements IEuler
Object answer()
Returns:

The answer to Project Euler problem 14

 1/*
 2Project Euler Problem 14
 3
 4This was easier to do in Java than I would have thought
 5
 6Problem:
 7
 8The following iterative sequence is defined for the set of positive integers:
 9
10n → n/2 (n is even)
11n → 3n + 1 (n is odd)
12
13Using the rule above and starting with 13, we generate the following sequence:
1413 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
15
16It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been
17proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
18
19Which starting number, under one million, produces the longest chain?
20
21NOTE: Once the chain starts the terms are allowed to go above one million.
22*/
23package euler;
24
25import java.util.HashMap;
26
27public class p0014 implements IEuler {
28    @Override
29    public Object answer() {
30        int biggestSeen = 0;
31        long biggestIdx = 0;
32        HashMap<Long, Integer> cache = new HashMap<Long, Integer>();
33        for (long x = 1; x < 1000000; x += 1) {
34            int result = collatzLen(x, cache);
35            if (result > biggestSeen) {
36                biggestSeen = result;
37                biggestIdx = x;
38            }
39        }
40        return (int) biggestIdx;
41    }
42
43    int collatzLen(long n, HashMap<Long, Integer> cache) {
44        if (n == 1)
45            return 0;
46        else if (cache.containsKey(n))
47            return cache.get(n);
48
49        int result;
50        if (n % 2 == 0)
51            result = 1 + collatzLen(n / 2, cache);
52        else
53            result = 2 + collatzLen((3 * n + 1) / 2, cache);
54        cache.put(n, result);
55        return result;
56    }
57}

Tags: collatz, recursion, longest-path