Reputation: 31
function primeSieve() {
for(i = 0; i <= 100; i++){
let flag = true
for(let j = 2; j < i/2; j++){
if(i % j === 0){
flag = false
}
}
if(flag){
console.log(i)
}
}
}
primeSieve();
Hi,
I'm studying some algos and ran into a prime sieve problem. I'm trying to print all prime numbers between 0 and 100 and it's working for the most part. However, i realized that 4 slipped in somehow and i can't figure out why for the life of me. Wondering if i can get a few pairs of eyes and see how 4 ended up being logged to the console and why that's the case.
thank you!
Upvotes: 2
Views: 36
Reputation: 386746
Beside the including the value for j
to check with j <= i / 2
, you could omit the use of a flag and use continue
with a label for the outer loop.
function primeSieve() {
outer: for (var i = 2; i <= 100; i++) {
for (var j = 2; j <= i / 2; j++) {
if (i % j === 0) {
continue outer;
}
}
console.log(i);
}
}
primeSieve();
Upvotes: 0
Reputation: 371059
Your condition in the inner loop:
for (let j = 2; j < i / 2; j++) {
is
j < i / 2
This means that when i
is 4, once j
gets to 2
(or, since j
is always initialized to 2, before the first iteration), the loop breaks. So, without any iterations, there's never any chance for an i
of 4
to get to flag = false
.
Change to
for (let j = 2; j <= i / 2; j++) {
Also, per wikipedia:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So you should probably start i
at 2, not 0.
Also, just like your let j
, it would be good to declare i
with let
as well so as not to implicitly pollute the global scope:
function primeSieve() {
for (let i = 2; i <= 100; i++) {
let flag = true
for (let j = 2; j <= i / 2; j++) {
if (i % j === 0) {
flag = false
}
}
if (flag) {
console.log(i)
}
}
}
primeSieve();
Upvotes: 2