Last active
August 29, 2015 14:03
-
-
Save forabi/304f881d89aeb14fb175 to your computer and use it in GitHub Desktop.
ECMAScript 6 implementation of Sieve of Eratosthenes algorithm https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function* getPrimes(n) { | |
let compos = []; | |
for (let i = 2; i <= n; i++) { | |
if (compos[i]) continue; | |
yield i; | |
for (let j = i * 2; j <= n; j += i) { | |
compos[j] = true; | |
} | |
} | |
} | |
function toArray(iterator) { | |
// Using array comprehensions (not supported in node v0.11.23): | |
// return [prime for (prime of iterator)]; | |
let array = []; | |
for (let prime of iterator) { | |
array.push(prime); | |
} | |
return array; | |
} | |
function print(n) { | |
for (let prime of getPrimes(n)) { | |
console.log(prime); | |
} | |
} | |
function benchmark(n, iterations) { | |
let start = new Date; | |
for (let j = 0; j < iterations; j++) { | |
toArray(getPrimes(n)); | |
} | |
return new Date - start; | |
} | |
console.log(benchmark(10000, 500)); | |
// print(10000000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment