Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Maths/MobiusFunction.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ export const mobiusFunction = (number) => {
return primeFactorsArray.length !== new Set(primeFactorsArray).size
? 0
: primeFactorsArray.length % 2 === 0
? 1
: -1
? 1
: -1
}
37 changes: 16 additions & 21 deletions Maths/SieveOfEratosthenes.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
const sieveOfEratosthenes = (n) => {
/*
* Calculates prime numbers till a number n
* :param n: Number up to which to calculate primes
* :return: A boolean list containing only primes
*/
const primes = new Array(n + 1)
primes.fill(true) // set all as true initially
primes[0] = primes[1] = false // Handling case for 0 and 1
const sqrtn = Math.ceil(Math.sqrt(n))
for (let i = 2; i <= sqrtn; i++) {
if (primes[i]) {
for (let j = i * i; j <= n; j += i) {
/*
Optimization.
Let j start from i * i, not 2 * i, because smaller multiples of i have been marked false.
/**
* Function to get all prime numbers below a given number
* This function returns an array of prime numbers
* @see {@link https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes}
*/

For example, let i = 4.
We do not have to check from 8(4 * 2) to 12(4 * 3)
because they have been already marked false when i=2 and i=3.
*/
primes[j] = false
function sieveOfEratosthenes(max) {
const sieve = []
const primes = []

for (let i = 2; i <= max; ++i) {
if (!sieve[i]) {
// If i has not been marked then it is prime
primes.push(i)
for (let j = i << 1; j <= max; j += i) {
// Mark all multiples of i as non-prime
sieve[j] = true
}
}
}
Expand Down
24 changes: 0 additions & 24 deletions Maths/SieveOfEratosthenesIntArray.js

This file was deleted.

12 changes: 5 additions & 7 deletions Maths/test/SieveOfEratosthenes.test.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { sieveOfEratosthenes } from '../SieveOfEratosthenes'
import { PrimeCheck } from '../PrimeCheck'

describe('should return an array of prime booleans', () => {
it('should have each element in the array as a prime boolean', () => {
const n = 30
describe('should return an array of prime numbers', () => {
it('should have each element in the array as a prime numbers', () => {
const n = 100
const primes = sieveOfEratosthenes(n)
primes.forEach((primeBool, index) => {
if (primeBool) {
expect(PrimeCheck(index)).toBeTruthy()
}
primes.forEach((prime) => {
expect(PrimeCheck(prime)).toBeTruthy()
})
})
})
12 changes: 0 additions & 12 deletions Maths/test/SieveOfEratosthenesIntArray.test.js

This file was deleted.

Loading
Loading