Skip to content

Commit 7c39839

Browse files
authored
merge: Add LinearSieve.js (TheAlgorithms#828)
1 parent 09eebc4 commit 7c39839

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Maths/LinearSieve.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const LinearSieve = (n) => {
2+
/*
3+
* Calculates prime numbers till a number n
4+
* Time Complexity: O(n)
5+
* Explanation: https://cp-algorithms.com/algebra/prime-sieve-linear.html
6+
* :param n: Number up to which to calculate primes
7+
* :return: A list containing only primes
8+
*/
9+
const isnPrime = new Array(n + 1)
10+
isnPrime[0] = isnPrime[1] = true
11+
const primes = []
12+
for (let i = 2; i <= n; i++) {
13+
if (!isnPrime[i]) primes.push(i)
14+
for (const p of primes) {
15+
const k = i * p
16+
if (k > n) break
17+
isnPrime[k] = true
18+
if (i % p === 0) break
19+
}
20+
}
21+
return primes
22+
}
23+
24+
export { LinearSieve }

Maths/test/LinearSieve.test.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { LinearSieve } from '../LinearSieve'
2+
import { PrimeCheck } from '../PrimeCheck'
3+
4+
describe('LinearSieve', () => {
5+
it('should return primes below 100', () => {
6+
expect(LinearSieve(100)).toEqual([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
7+
})
8+
9+
it('should return primes only', () => {
10+
const n = 100000
11+
const primes = LinearSieve(n)
12+
for (const p of primes) {
13+
expect(PrimeCheck(p)).toBeTruthy()
14+
}
15+
})
16+
})

0 commit comments

Comments
 (0)