Last active
August 11, 2016 21:25
-
-
Save tvararu/ed0539945e24312b1b3ccb237d1b57e8 to your computer and use it in GitHub Desktop.
This file contains 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
// Print out all the prime numbers from 1 to 100. | |
const N = 100 | |
const range = (k) => Array.from(Array(k).keys()) | |
const multiples = (i, max) => range(Math.ceil(max / i - 1)).map((k) => i * (k + 1)) | |
const sieve = range(N) | |
.reduce((s, i) => { | |
if (i === 0) { s[i] = false } | |
if (i === 1) { s[i] = true } | |
if (s[i] === undefined) { | |
multiples(i, N).forEach((k) => s[k] = false) | |
s[i] = true | |
} | |
return s | |
}, Array(N)) | |
sieve.forEach((k, idx) => (k) ? console.log(idx) : '') |
This file contains 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
// Print out all the prime numbers from 1 to 100. | |
const N = 100 | |
const range = (k) => Array.from(Array(k).keys()) | |
const multiples = (i, max) => range(Math.ceil(max / i - 1)).map((k) => i * (k + 1)) | |
let sieve = Array(N).fill(true) | |
sieve[0] = false | |
for (let i = 2; i < N; i++) { | |
if (sieve[i]) { | |
multiples(i, N).forEach((k) => sieve[k] = false) | |
sieve[i] = true | |
} | |
} | |
sieve.forEach((k, idx) => (k) ? console.log(idx) : '') |
This file contains 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
// Print out all the prime numbers from 1 to 100. | |
const N = 100 | |
let sieve = Array(N).fill(true) | |
sieve[0] = false | |
for (let i = 2; i < N; i++) { | |
if (sieve[i]) { | |
for (let j = i + i; j < N; j += i) { | |
sieve[j] = false | |
} | |
} | |
} | |
sieve.forEach((k, idx) => (k) ? console.log(idx) : '') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment