Trouble with a Prime Number Finder Code

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

I tried making a code that will find prime numbers, add them to a list of prime numbers, then ask if you want to continue the code to find the next prime number.
<Below this line, add a link to the EXACT exercise that you are stuck at.>
This isn’t a exercise in the courses, but a personal project.

<In what way does your code behave incorrectly? Include ALL error messages.>
Currently, it seems to have a infinite loop going on, so my browser freezes before giving me the “unresponsive script” popup.

```

var P = [2];
var c = true;
var s = 3;
var m = 0;
var e = 0;
var f = true;

var dividing = function(x) {
return(x%P[m]);
};

while © {
m = 0;
while (f) {
if (dividing(s)!==0) {
m = m + 1;
if (m === (P.length)) {
P.push(s);
f = false;
e = e+1;
}
}
else {
f = false;
}
}
s=s+1;
if (e===1) {
c = confirm(“Would you like to continue?”);
}
e=0;
}
console.log§;

<do not remove the three backticks above>

Did you mean to return this value?

1 Like

Yes, I fixed it but for some reason it still isn’t working.
The option to continue pops up but if I press OK the browser freezes (If I press cancel the console shows [ 2, 3 ]).

You might have to write this inside the while © loop body.

Outside of the loop, delcare the variable

var f;
while (c) {
    f = true;
    // ...
}
1 Like

Thank you, this fixed it, I understand why it didn’t work now, so thank you very much.

1 Like

Testing your code with this:

var P;
var dividing = function(x) {
        return(x%P[m]);
    };
var first_n_primes = function (n) {
    var s = 3;
    var m = 0;
    var e = 0;
    var f;
    P = [2];
    while (n > 1) {
        f = true;
        m = 0;
        while (f) {
            if (dividing(s)!==0) {
                m = m + 1;
                if (m === (P.length)) {
                    P.push(s);
                    f = false;
                    e = e+1;
                    n--;
                }
            }
            else {
                f = false;
            }
        }
        s=s+1;
        e=0;
    }
    console.log(P);
};
 > first_n_primes(20)

[ 2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ]
                          x           x       x   x           x           x