I have been trying to write Sieve of Eratosthenes algorithm in JavaScript. Basically I just literally followed the steps below:
Just for the fun of it, I implemented the Erastoten sieve algorithm (run with Node) strictly following the rules of TDD. This version should be enough for interviews, as a school exercise or just like I was - for messing around a bit.
Let me state, that I definitely think the accepted answer should be the one provided by GordonBGood.
module.exports.compute = function( size )
{
if ( !utils.isPositiveInteger( size ) )
{
throw new TypeError( "Input must be a positive integer" );
}
console.time('optimal');
console.log();
console.log( "Starting for optimal computation where size = " + size );
let sieve = utils.generateArraySeq( 2, size );
let prime = 2;
while ( prime )
{
// mark multiples
for ( let i = 0; i < sieve.length; i += prime )
{
if ( sieve[i] !== prime )
{
sieve[i] = -1;
}
}
let old_prime = prime;
// find next prime number
for ( let i = 0; i < sieve.length; i++ )
{
if ( ( sieve[i] !== -1 ) && ( sieve[i] > prime ) )
{
prime = sieve[i];
break;
}
}
if ( old_prime === prime )
{
break;
}
}
console.timeEnd('optimal');
// remove marked elements from the array
return sieve.filter(
function( element )
{
return element !== -1;
} );
} // compute
I will appreciate any senseful critique.
The whole repository can be found on my github account.