Who is storing prime numbers is the method push()
The method push()
adds one or more elements at the end of an array and returns the new length of that array.
The symbol of the operator %
is called the module operator. The result of an operation with this operator generates the remainder of the division of two values. If the rest is zero, then the first value can be divided exactly by the second.
Arithmetic is useful for those occasions when you want to know if one number is perfectly divisible by another
The variable quantidadeDeDivisores
is a variable that quantifies the numbers of divisors of i
for b
the rest of which is zero 0
Run the code below by clicking Run at the end of this reply and note that when the variable quantidadeDeDivisores
is zero means to be a prime number and is stored in the array.
function buscaNumeroPrimos(n) {
var numerosPrimos = [];
for (var i = 2; i < n; i++){ //Armazenou os números de 2 a 9
var quantidadeDeDivisores = 0;
var explica = (" Para i = " + i);
for(var b = 2; b < i; b++) { //Armazenou os números de 2 a 9
explica += (" ; b = " + b);
//se o resto dessa divisão for 0 é um divisor e incrementa quantidadeDeDivisores
if (i % b == 0) {
quantidadeDeDivisores ++;
}
}
console.log(" ");
explica +=(" quantidadeDeDivisores = " + quantidadeDeDivisores);
console.log(explica);
//if (quantidadeDeDivisores == 0) {
if (quantidadeDeDivisores % i == 0) {
numerosPrimos.push(i);
console.log(numerosPrimos);
}
}
return numerosPrimos;
}
buscaNumeroPrimos(20);
"...I know she’s storing the prime numbers...", not!
quantidadeDeDivisores
is not storing the prime numbers, it is actually a counter used to add one to one the number of divisors ofi
smaller thani
. It works as follows,b
varies from2
untili
at each variation ofb
is made a testi % b == 0
if the rest ofi
divided byb
for0
implies thatb
is a divider ofi
and then is added1
quantidadeDeDivisores
. At the end of the iteration ifquantidadeDeDivisores
is non-zero means that the number is not prime.– Augusto Vasques
Thank you very much Augusto.
– Caio Filipe