Euler 14

JavaScript performance comparison

Revision 3 of this test case created

Info

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?

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
No Cache
var sequence = function( num, count ){
        var val;
        if ( num % 2 == 0 )
                val = num / 2;
        else
                val = ( num * 3 ) + 1;
        if ( val == 1 ) return count;
        return sequence( val, count + 1 );
},
num,
max = 0;
for ( var i = 1; i < 9999; i++ ){
        var val = sequence( i, 1 );
        if ( val > max ) {
                num = i;
                max = val;
        }
}
return num;
pending…
Cache
var cache = {},
sequence = function( num, count ){
        var val;
        if ( cache[num] ) return count + cache[num];
        if ( num % 2 == 0 )
                val = num / 2;
        else
                val = ( num * 3 ) + 1;
        if ( val == 1 ) return count;
        return sequence( val, count + 1 );
},
num,
max = 0;
for ( var i = 1; i < 9999; i++ ){
        var val = sequence( i, 1 );
        cache[i] = val;
        if ( val > max ) {
                num = i;
                max = val;
        }
}
return num;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment