Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Linear prime sieve #219

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Next Next commit
Add linear prime sieve
sandeeps456 committed Sep 24, 2018
commit 01f14089a5737c0fec5ccbd0612f63ff7132fa3e
24 changes: 24 additions & 0 deletions src/algorithms/math/linear-prime-sieve/linearPrimeSieve.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @param {number} maxNumber
* @return {number[]}
*/
export default function linearPrimeSieve(maxNumber) {
const primes =[];
const leastPrimeFactor = new Array(maxNumber + 1).fill(0); // leastPrimeFactor[i] gives us the least prime factor of 'i'

for(let i=2; i<=maxNumber; i++ ){
if(!leastPrimeFactor[i]){ // leastPrimeFactor[i] = 0 means 'i' itself is its least prime factor, i.e 'i' is prime
leastPrimeFactor[i] = i;
primes.push(i);
}

/*
* start setting leastPrimeFactor[] for numbers 'x', where x = p * i, p is x's least prime factor and p <= leastPrimeFactor[i]
* x = p*i, this representation will be unique for any number, therefore leastPrimeFactor[x] will be set only once.
*/
for(let j=0; j<primes.length && primes[j]*i <=maxNumber && primes[j]<=leastPrimeFactor[i]; j++)
leastPrimeFactor[primes[j]*i] = primes[j];
}

return primes;
}