Trouble with a Prime Number Finder Code

project
javascript

#1



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.

This isn't a exercise in the courses, but a personal project.


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 (c) {
    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(P);


#2

Did you mean to return this value?


#3

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 ]).


#4

You might have to write this inside the while (c) loop body.

Outside of the loop, delcare the variable

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

#5

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


#6

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