Skip to content

Commit 0084acf

Browse files
authored
algorithm: sieve (TheAlgorithms#1205)
1 parent 55f502e commit 0084acf

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Maths/SieveOfEratosthenesIntArray.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Function to get all prime numbers below a given number
3+
* This function returns an array of prime numbers
4+
* @see {@link https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes}
5+
*/
6+
7+
function sieveOfEratosthenes (max) {
8+
const sieve = []
9+
const primes = []
10+
11+
for (let i = 2; i <= max; ++i) {
12+
if (!sieve[i]) { // If i has not been marked then it is prime
13+
primes.push(i)
14+
for (let j = i << 1; j <= max; j += i) { // Mark all multiples of i as non-prime
15+
sieve[j] = true
16+
}
17+
}
18+
}
19+
return primes
20+
}
21+
22+
export { sieveOfEratosthenes }
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { sieveOfEratosthenes } from '../SieveOfEratosthenesIntArray'
2+
import { PrimeCheck } from '../PrimeCheck'
3+
4+
describe('should return an array of prime numbers', () => {
5+
it('should have each element in the array as a prime numbers', () => {
6+
const n = 100
7+
const primes = sieveOfEratosthenes(n)
8+
primes.forEach(prime => {
9+
expect(PrimeCheck(prime)).toBeTruthy()
10+
})
11+
})
12+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy