Skip to content

Commit 296e8f0

Browse files
authored
algorithm: sieve of erastosthenes (#74)
* Sieve Of Eatosthenes implementation * Test addition
1 parent 538abac commit 296e8f0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Maths/SieveOfEratosthenes.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function SieveOfEratosthenes
3+
* @description Find the prime numbers between 2 and n
4+
* @param {number} n - numbers set the limit that the algorithm needs to look to find the primes
5+
* @return {number[]} - List of prime numbers
6+
* @see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\
7+
* @example SieveOfErastosthenes(5) = [2,3,5]
8+
* @example SieveOfErastosthenes(10) = [2,3,5,7]
9+
*/
10+
11+
export function SieveOfEratosthenes(n: number): number[] {
12+
if (n < 0 || !Number.isInteger(n)) {
13+
throw new Error("Only natural numbers are supported");
14+
}
15+
const numbers = new Array<boolean>(n + 1)
16+
.fill(true)
17+
const primeNumbers: number[] = [];
18+
for (let i = 2; i <= n; i++) {
19+
if (numbers[i]) {
20+
primeNumbers.push(i);
21+
for (let j = i + i; j <= n; j += i) {
22+
numbers[j] = false;
23+
}
24+
}
25+
}
26+
return primeNumbers;
27+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { SieveOfEratosthenes } from "../SieveOfEratosthenes";
2+
3+
4+
describe("Sieve of Eratosthenes", () => {
5+
test.each([-2, 0.1, -0.01, 2.2])(
6+
"should throw a error for non natural number",
7+
(n) => {
8+
expect(() => SieveOfEratosthenes(n)).toThrow(
9+
"Only natural numbers are supported"
10+
);
11+
},
12+
);
13+
14+
test.each([[5, [2, 3, 5]], [11, [2, 3, 5, 7, 11]], [30, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]]])(
15+
"of %i should be %o",
16+
(num, expected) => {
17+
expect(SieveOfEratosthenes(num)).toStrictEqual(expected);
18+
},
19+
);
20+
});

0 commit comments

Comments
 (0)