Sieve of Eratosthenes algorithm in JavaScript running endless for large number

后端 未结 7 1988
孤街浪徒
孤街浪徒 2020-11-30 02:47

I have been trying to write Sieve of Eratosthenes algorithm in JavaScript. Basically I just literally followed the steps below:

  1. Create a list of consecutive in
7条回答
  •  囚心锁ツ
    2020-11-30 03:03

    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.

提交回复
热议问题