I am trying to write a script which displays the prime numbers from 0 to 100, but when I execute it, the browser crashes. JSHint didn't detect any error.
I'd like to learn why this code doesn't work: I am not interested in finding a totally different code( like this one) that completes the same task.
This is the first code I've ever written, so I apologise in advance for all the silly mistakes I overlooked.
var i;
var m;
var primeArr = [2, 3, 5, 7, 11, 13, 17, 19];
var theMaxNumber = 100;
var theMinNumber = 21;
var theCounter = -1;
function myFunction() {
for (i = theMinNumber; i < theMaxNumber; i += 2) {
for (m = 0; m < primeArr.length; m++) {
if (i % primeArr[m] !== 0) {
theCounter++;
if (theCounter === primeArr.length) {
primeArr.push(i);
}
if (m === primeArr.length) {
theCounter = -1;
}
}
}
}
console.log( primeArr.toString());
}
This is how it should work in theory:
1) the function finds out whether or not the number i is divisible for a prime number smaller then itself.
2) In case it is, theCounter is resetted and i is incremented by two.
3) In case it isn't, theCounter is incremented by one. If, at the end of the cycle, i is not divisibile for all the prime numbers smaller than itself, it means that it's a prime number: i is pushed in the array (because theCounter = == primeArr.length), then i is incremented by two.
edit: I fixed all the errors in the code, it works perfectly now:
var i;
var m;
var primeArr = [3, 5, 7, 11, 13, 17, 19];
var theMaxNumber = 100;
var theMinNumber = 21;
var theCounter = 0;
function myFunction() {
for (i = theMinNumber; i < theMaxNumber; i += 2) {
theCounter = 0;
for (m = 0; m < primeArr.length; m++) {
if (i % primeArr[m] !== 0) {
theCounter++;
}
if (theCounter === primeArr.length) {
primeArr.push(i);
}
}
}
primeArr.unshift(2);
console.log( primeArr.toString());
}