Skip to content

Commit b8f1552

Browse files
committed
Fixes #1666: Remove duplicate entry of Sieve of Eratosthenes
1 parent 5b17ea1 commit b8f1552

7 files changed

+661
-364
lines changed

Maths/MobiusFunction.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,6 @@ export const mobiusFunction = (number) => {
2828
return primeFactorsArray.length !== new Set(primeFactorsArray).size
2929
? 0
3030
: primeFactorsArray.length % 2 === 0
31-
? 1
32-
: -1
31+
? 1
32+
: -1
3333
}

Maths/SieveOfEratosthenes.js

+16-21
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
1-
const sieveOfEratosthenes = (n) => {
2-
/*
3-
* Calculates prime numbers till a number n
4-
* :param n: Number up to which to calculate primes
5-
* :return: A boolean list containing only primes
6-
*/
7-
const primes = new Array(n + 1)
8-
primes.fill(true) // set all as true initially
9-
primes[0] = primes[1] = false // Handling case for 0 and 1
10-
const sqrtn = Math.ceil(Math.sqrt(n))
11-
for (let i = 2; i <= sqrtn; i++) {
12-
if (primes[i]) {
13-
for (let j = i * i; j <= n; j += i) {
14-
/*
15-
Optimization.
16-
Let j start from i * i, not 2 * i, because smaller multiples of i have been marked false.
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+
*/
176

18-
For example, let i = 4.
19-
We do not have to check from 8(4 * 2) to 12(4 * 3)
20-
because they have been already marked false when i=2 and i=3.
21-
*/
22-
primes[j] = false
7+
function sieveOfEratosthenes(max) {
8+
const sieve = []
9+
const primes = []
10+
11+
for (let i = 2; i <= max; ++i) {
12+
if (!sieve[i]) {
13+
// If i has not been marked then it is prime
14+
primes.push(i)
15+
for (let j = i << 1; j <= max; j += i) {
16+
// Mark all multiples of i as non-prime
17+
sieve[j] = true
2318
}
2419
}
2520
}

Maths/SieveOfEratosthenesIntArray.js

-24
This file was deleted.
+5-7
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import { sieveOfEratosthenes } from '../SieveOfEratosthenes'
22
import { PrimeCheck } from '../PrimeCheck'
33

4-
describe('should return an array of prime booleans', () => {
5-
it('should have each element in the array as a prime boolean', () => {
6-
const n = 30
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
77
const primes = sieveOfEratosthenes(n)
8-
primes.forEach((primeBool, index) => {
9-
if (primeBool) {
10-
expect(PrimeCheck(index)).toBeTruthy()
11-
}
8+
primes.forEach((prime) => {
9+
expect(PrimeCheck(prime)).toBeTruthy()
1210
})
1311
})
1412
})

Maths/test/SieveOfEratosthenesIntArray.test.js

-12
This file was deleted.

0 commit comments

Comments
 (0)