Sieve of Eratosthenes algorithm in JavaScript running endless for large number

后端 未结 7 1987
孤街浪徒
孤街浪徒 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:13

    I would post this as a comment to Alexander, but I don't have the reputation to do that. His answer is awesome, and this just tweaks it to make it faster. I benchmarked by testing n = 100,000,000.

    Instead of using true and false in 'array', I get a big speed boost by using 1 and 0. This reduced my time in Chrome from 5000 ms to 4250 ms. Firefox was unaffected (5600 ms either way).

    Then we can take into account that even numbers will never be prime. Put 2 into 'output' off the bat and you can do i=3; i += 2, and j += i*2 during the sieve (we can skip the even multiples since any number times an even number is even), as long as we also i += 2 while pushing to 'output' at the end. This reduced my time in Chrome from 4250 ms to 3350 ms. Firefox benefited a bit less, dropping from 5600 ms to 4800 ms.

    Anyway, the combination of those two tweaks gave me a 33% speed boost in Chrome, and a 14% boost in Firefox. Here's the improved version of Alexander's code.

    var eratosthenes = function(n) {
        // Eratosthenes algorithm to find all primes under n
        var array = [], upperLimit = Math.sqrt(n), output = [2];
    
        // Make an array from 2 to (n - 1)
        for (var i = 0; i < n; i++)
            array.push(1);
    
        // Remove multiples of primes starting from 2, 3, 5,...
        for (var i = 3; i <= upperLimit; i += 2) {
            if (array[i]) {
                for (var j = i * i; j < n; j += i*2)
                    array[j] = 0;
            }
        }
    
        // All array[i] set to 1 (true) are primes
        for (var i = 3; i < n; i += 2) {
            if(array[i]) {
                output.push(i);
            }
        }
    
        return output;
    };
    

提交回复
热议问题