Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created February 26, 2019 18:05
Show Gist options
  • Save okovalov/c78d6ec14a4d130a3db06acd88d7b94c to your computer and use it in GitHub Desktop.
Save okovalov/c78d6ec14a4d130a3db06acd88d7b94c to your computer and use it in GitHub Desktop.
const sieveOfErathosphenes = num => {
const arr = [false, false]
for (let idx = 2; idx < num; idx ++) {
arr[idx] = true
}
for (let i = 2; i < Math.sqrt(num); i++) {
for (let j = 2; j * i <= num; j++) {
arr[i * j] = false
}
}
return arr.map((el, idx) => el ? idx : 0).filter(el => el)
}
const result = sieveOfErathosphenes(30)
console.time('test')
console.log(result) // [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ] test: 6.255ms
console.timeEnd('test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment