Nosh Brinken - 1 year ago 93

Javascript Question

I'm trying to write a JavaScript prime number generator that lists every prime between 1 and 100. I know this is a common programming exercise and there's an abundance of solutions on the web. My question is why does my solution result an empty array? Here's the code:

`var primeNumbers = [];`

for (var x=2; x<101; x++)

if (x%2 === 0)

{

break;

}

else

{

for (var y=2; y<101; y++)

{

if (x/y > 1)

{

break;

}

else

{

primeNumbers.push(x);

}

}

}

};

console.log(primeNumbers);

Answer Source

**Problem 1:** You break when `x%2 === 0`

, so you exit the loop at once. Reverse the condition and enter the code in the loop directly:

Replace this:

```
if (x%2 === 0) {
break;
}
else {
```

with:

```
if (x%2 !== 0) {
```

**Problem 2:** You are exiting the inner loop if `x/y > 1`

. This is the same as the condition `x > y`

, so that will always exit the inner loop immediately. Instead make the inner loop run from two and up to one less than `x`

:

```
for (var y=2; y<x; y++) {
```

**Problem 3:** Instead of dividing `x`

by `y`

and comparing to one, you should use the modulo operator: `x%y`

. If the result is zero, then `x`

is not a prime number.

**Problem 4:** You are adding prime numbers inside the inner loop, so you will end up with most numbers multiple times, not just prime numbers once.

You need to add a variable to keep track of what's happening in the inner loop. If *none* of the checks in the inner loop are zero, then you can add `x`

to the list of prime numbers.