3n + 1 Problem

a programming challenge

by Hugh Chapman

HTML

<h1>The 3n + 1 Problem</h1>

<p>Take two input pairs. For each integer between and including the pair output the maximum cycle length - the number of integer steps - in the following algorithm: If i is even, divide by two. If i is odd multiply by 3 and add 1. Repeat this process on the result n until the value of 1 is reached.</p>
<form id='pair'>
    <input id='i' type='number' name='i' value='' />
    <input id='j' type='number' name='j' value='' />
    <input type='submit' name='Submit' value="Calculate"/>
</form>
<div id="output"></div>

CSS

#output { margin-top: 20px;}

JavaScript

var element = window.document.getElementById('pair');
var calculate = function(e) {
    e.preventDefault();
    var selector = '#' +e.currentTarget.id;
    var i = parseInt(document.querySelector(selector).i.value,0);
    var j = parseInt(document.querySelector(selector).j.value,0);
    if(!i || !j) return;
    if (j < i) j = [i, i = j][0]; // ascending order
    var output = document.querySelector('#output'); 
    console.log(output);
    var max = 1;
    for(var x = i; x <= j; x++) {
        var set = [];
        var n = x;
        while (n !== 1) {
            set.push(n);
            n = cycle(n);    
        }
        set.push(n); // add the last value of 1 to array
        max = (set.length > max) ? set.length : max;
        console.log(max);
        console.log(set);
    }
    if (output.textContent) {
        output.textContent = i + ' ' + j + ' ' + max;
    } else {
        output.innerText = i + ' ' + j + ' ' + max; // ie < 9
    }
    console.log('done.');
};

function cycle(n) {
    return (n % 2 === 0) ? n/2 : (n * 3) + 1;   
}

element.addEventListener('submit', calculate, false);