Created
March 6, 2023 15:21
-
-
Save LucianBuzzo/b9ff584ae6ff741659a8bd11479dace1 to your computer and use it in GitHub Desktop.
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
| const primeSeive = (n) => { | |
| const primes = [] | |
| // Start with an array of all numbers between 2 and n | |
| let buf = Array(n - 1).fill().map((_, i) => i + 2); | |
| let pointer = 0; | |
| while (pointer < buf.length) { | |
| const p = buf[pointer]; | |
| // Push the prime | |
| primes.push(p); | |
| // Remove all multiples of p from the buf skipping the first one | |
| for (let i = pointer + p; i < buf.length; i += p) { | |
| buf[i] = null; | |
| } | |
| // Advance the pointer to the next non null number; | |
| do { | |
| pointer += 1; | |
| } while(buf[pointer] === null) | |
| } | |
| return primes; | |
| } | |
| console.log(primeSeive(100)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment