C++ Implementation of Problem 14

View source code here on GitHub!

Includes

Solution

uint64_t p0014()
int main(int argc, char const *argv[])

Note

This function is only present in the Python test runner, or when compiling as a standalone program.

 1/*
 2Project Euler Problem 14
 3
 4This was easier to do in C++ 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*/
23#ifndef EULER_P0014
24#define EULER_P0014
25#include <stdint.h>
26#include <iostream>
27#include "include/macros.hpp"
28
29#define CACHE_SIZE 1000000
30static uint32_t collatz_len_cache[CACHE_SIZE] = {0, 1, 0};
31
32uint32_t collatz_len(uint64_t n);
33uint32_t collatz_len(uint64_t n) {
34    if (n < CACHE_SIZE && collatz_len_cache[n])
35        return collatz_len_cache[n];
36    uint32_t ret = 0;
37    if (n % 2)
38        ret = 2 + collatz_len((3 * n + 1) / 2);
39    else
40        ret = 1 + collatz_len(n / 2);
41    if (n < CACHE_SIZE)
42        collatz_len_cache[n] = ret;
43    return ret;
44}
45
46uint64_t EMSCRIPTEN_KEEPALIVE p0014() {
47    uint64_t answer = 2, length = 2, tmp;
48    for (uint64_t test = 3; test < 1000000; test++) {
49        tmp = collatz_len(test);
50        if (tmp > length) {
51            answer = test;
52            length = tmp;
53        }
54    }
55    return answer;
56}
57
58PROGRAM_TAIL(p0014)
59#endif

Tags: collatz, recursion, longest-path