Collatz sequence stopping time for first 1,000 integers

Collatz sequence stopping time for first 1,000 integers

The Collatz sequence is defined by the following rule:

n = n/2 if n is even
n = 3n + 1 if n is odd

Based on this rule and starting with 20; the following sequence is generated:

20 – 10 – 5 – 16 – 8 – 4 – 2 – 1


var math = require('mathjs');
var log = console.log;

var integer = function(n) {
        var output = [];
        for(ii = 1; ii <= n; ii++) {
                output.push(ii);
        }
        return output;
};

var collatz = function(k) {
        var output = [k];
        var n = k;
        while(n > 1) {
                if(n % 2 === 0) {
                        n /= 2;
                        output.push(n);
                } else {
                        n = (3*n + 1);
                        output.push(n);
                }
        }
        return output.length;
}

var colsearch = function(j) {
        var intlist = integer(j);
        var output = [];
        for(ii in intlist) {
                output.push(collatz(intlist[ii]));
        }
        return output;
}

var isearch = function(as) {
        var output = [];
        var max = math.max(as);
        var acc = 0;
        for(ii in as) {
                if(as[ii] === max) {
                        acc = Number(ii) + 1;
                        output.push(acc);
                }
        }
        return output;
};

Using this code the starting number up to 1 million which produces the longest Collatz sequence is 837799

Advertisement