It should be continue primes_loop
instead of break primes_loop
. Currently when it reaches a composite number (the first being 9 as it is incrementing by 2) it breaks out of the outer loop and stops the search entirely instead of just skipping that number.
Why does this prime number generator only work on primes up to 7?
-
22-06-2023 - |
Question
I noticed this question on Code Review and decided to play with one of the answers' JSfiddles to look at a long list of primes. However, his answer only reached 7. Why?
function findPrimes(lowerLimit, upperLimit) {
var primes = []; // will become a list of prime numbers
if (lowerLimit === 2) {
primes.push(2);
}
if (lowerLimit % 2 === 0) {
lowerLimit++;
}
primes_loop: for (var n = lowerLimit; n < upperLimit; n = n + 2) {
for (var i = 2; i < n; i++) {
if (n % i === 0) {
break primes_loop; // n is not prime if condtion is ture
}
}
primes.push(n); // update prime list with the prime number
}
for (var index = 0; index < primes.length; index++) {
$("#body").append(primes[index] + '<br/>');
}
}
findPrimes(2, 150);
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow