Code
var c = 100;
var j = 2;
var numerosPrimos = [];
for (; j < c; j++) {
if (primo(j)) {
numerosPrimos.push(j);
}
}
console.log(numerosPrimos);
function primo(numero) {
for (var i = 2; i < numero; i++) {
if (numero % i === 0) {
return false;
}
}
return numero !== 1;
}
Explanation
Note: Prime numbers are those that can only be divisible by themselves and by number one.
Therefore, we have created the function:
function primo(numero) {
for (var i = 2; i < numero; i++) {
if (numero % i === 0) {
return false;
}
}
return numero !== 1;
}
That in more natural language does the following:
Having a numero
we iterate from 2 to the value of numero - 1
and in each iteration we verify if any of those numbers is divisible with numero
, if so, we return FALSE
otherwise we verify that the number entered is not 1 since this is not considered a prime number. And if the number evaluated was not 1, then we return TRUE, but return FALSE.
Therefore in this loop:
for (; j < c; j++) {
if (primo(j)) {
numerosPrimos.push(j);
}
}
We begin to go through each of the numbers in the iteration by checking through the function primo()
if the number is prime and add it to the array.
Update
Due to the comments I have seen, it seems that it has not been clear to you how this algorithm works, I explain it step by step.
Having the following function:
Execute the Snippet to see the operation step by step.
function primo(numero) {
console.log("Has pasado el numero: " + numero);
console.log("Inicio bucle desde 2 hasta " + (numero - 1));
for (var i = 2; i < numero; i++) {
console.log("Modulo entre " + numero + " y " + i + " = " + (numero % i));
if (numero % i === 0) {
console.log(i + " es un multiplo de " + numero);
console.log(numero + " no es un numero primo porque " + i + " es un multiplo");
return false;
}
}
if (numero === 1) {
console.log("Me has pasado el numero 1, recuerda que NO es un numero primo");
} else {
console.log("Como el numero ingresado no tuvo mas múltiplos entonces determinamos que SI es un numero primo.");
}
console.log("-------------------------------------");
}
primo(2);
primo(4);
primo(5);
primo(10);