52
loading...
This website collects cookies to deliver better user experience
let sample_array = [2, 3, 4, 5, 6, 7, 8, 9, 10];
let sample_array = [2, 3, 4*, 5, 6*, 7, 8*, 9, 10*];
let sample_array = [2, 3, 4*, 5, 6*, 7, 8*, 9*, 10*];
let sample_array = [2, 3, 5, 7];
Boolarray
, why naming 'Bool', because we are going for a Boolean array. We also initialize the value of n as 20.let Boolarray = [];
let n = 20;
true
for is prime
and false
for not a prime
, with this in mind we first fill the empty array with boolean values of all True
(based on our assumption). We use a for
loop with iterator i
to iterate from 1 to n and fill the array with True
.let Boolarray = [];
let n = 20;
for (var i = 0; i < n; i++) {
Boolarray.push(true);
}
true
on all indexes. We now follow the procedure of Sieve of Eratosthenes by starting the for
with iterator j
from 2 to j*j<=n (j*j<=n checks when to end the looping). If the current element in the array is true
, we then loop over its multiples with iterator k
and a step count, (according to the current element) and mark them false
.let Boolarray = [];
let n = 20;
for (var i = 0; i < n; i++) {
Boolarray.push(true);
}
for (let j = 2; j * j <= n; j++) {
if (Boolarray[j] == true) {
for (let k = 2 * j; k <= n; k += j) {
Boolarray[k] = false;
}
}
}
true
in places of prime (remember true
→ is prime) and false
in places of non-prime numbers in the array.for
loop to iterate on Boolarray
with iterator num
, starting from 2 to num<=n. We console log only the num
's which contains true
in the Boolarray
.for (let num = 2; num <= n; num++) {
if (Boolarray[num] == true) {
console.log(num);
}
}
n
to your wish.