Euler Problem 14

Longest Collatz sequence

by Andrew Poes

HTML

<!-- The following iterative sequence is defined for the set of positive integers:

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

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million. -->

CSS

.print {
    position: relative;
    display: inline-block;
    background-color: black;
    color: white;
    font-family: Helvetica, Helvetica-Neue, sans-serif;
    font-weight: bold;
    font-size: 24px;
    letter-spacing: -1.5px;
    padding: 4px 8px;
}

body {
    background-color: #eeeeee;
}
}

JavaScript

$(document).ready(function() {
	var start = new Date().getTime();
	
	var s = 1000000
    var largestNum = s
    var largestSeq = 0
    var cache = []
    for (var i = 0; i < s; ++i) {
        cache[i] = -1
    }
    for (var i = 2; i < s; ++i) {
        var sequence = i
        var count = 0
        while (sequence != 1 && sequence >= i) {
            sequence = collatz(sequence)
            ++count
        }
        // store cache with count + sequence length of end of sequence
        cache[i] = count + cache[sequence]
        
        if (cache[i] > largestSeq) {
            largestSeq = cache[i]
            largestNum = i
        }
    }
    print(largestNum, largestSeq)
    
    var end = new Date().getTime();
    var time = end - start;
	print('Execution time: ' + time + 'ms');
})

function collatz(n) {
    if (n%2 == 0) {
        return n / 2
    }
    else {
        return n * 3 + 1
    }
}

function print() {
    var args = Array.prototype.slice.apply(arguments)
    var str = ""
    for (arg of args) {
        str += arg + ", "
    }
    str = str.substring(0, str.length - 2)
    var el = newel(str)
    $("body").append(el)
    $("body").append("</br>")
}

function newel(str) {
    var el = document.createElement("div")
    $(el).html(str)
    $(el).addClass("print")
    return el
}