I had to look up some other solutions online because I could not figure it out on my own. I really wish I could have come up with it completely on my own, but that didn't happen. Nevertheless, please review my prime number program and let me know if there are any improvements I should make or advice your would like to give me about it.
var primes = []; // will become a list of prime numbers
primes_loop:
for (var n = 2; n < 10; n++) {
if (n === 2) {
primes.push(n); // first prime number is stored
continue primes_loop; // continue iteration of the loop
}
divisors_loop:
for (var i = 2; i < n; i++) {
if (n % i === 0) {
break divisors_loop; // n is not prime if condition is true
}
else {
primes.push(n); // update prime list with the prime number
}
}
}
for (var index = 0; index < primes.length; index++) {
console.log(primes[index]);
}
for (var i = 2; i < n; i++)
I am kind of against using this kind of a loop, the number of iterations can be reduced by half just by changing it to,for (var i = 2; i < n/2; i++)
Furthermore, if we are testing a very large number to be prime or not, usingi=2 ; i< sqrt(n) ; i++
reduces the number of iterations exponentially. (the last code snippet was a C code, not sure about the sqrt() function in javascript) \$\endgroup\$n
is the number that is being tested for being prime or not, while the loop condition that is mentioned is for testing if a number is prime or not. Lets consider n=11, then the loop runs from i=2; i<5, no divisors found and hence prime. for a number n, the number of factors from [1,n/2] is equal top the number of factors from [n/2,n] hence the second part of the iteration is a repeat of the first part. I will try and fetch the algo that proves it. \$\endgroup\$for (var n = 2; n < 10; n++)
for generating the range of numbers from which he will print the ones that are prime, andfor (var i = 2; i < n; i++)
that tests if the generated number is prime or not. The value ofn
that is being generated in the first loop is being used as the upper limit for the second loop that tests if the number is primie or not. This is the loop that I am referring to. \$\endgroup\$[2, floor(sqrt(n))]
to determine primality ofn
. \$\endgroup\$