Hi everyone,
I’m stuck on the “Sum All Primes” challenge and was wondering if anyone from the community can help see what’s wrong with my code, thanks in advance.
Link to exercise: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes
At this point I’m not even at the stage where I can add up all the prime numbers. All I want to do is create an array of prime numbers that is less than or equal to the “num” that is passed in.
function sumPrimes(num) {
let arrayOfPrimeNumbers = [2, 3];
let counter = 1;
// I found a formula on the internet which states that apart from the numbers 2 and 3, the way to find prime numbers is...
// 6(1) - 1;
// 6(1) + 1;
// 6(2) - 1;
// 6(2) + 1; etc.
let formula1 = (6 * counter) - 1;
let formula2 = (6 * counter) + 1;
// I'm saying, while the last value in the array is less than or equal to "num", execute the code.
while (arrayOfPrimeNumbers[arrayOfPrimeNumbers.length - 1] <= num) {
if (formula1 <= num) {
arrayOfPrimeNumbers.push(formula1);
} else {
break; // I want to end the "while" loop if it is not the case that formula1 is less than or equal to num.
}
if (formula2 <= num) {
arrayOfPrimeNumbers.push(formula2);
} else {
break; // I want to end the "while" loop if it is not the case that formula2 is less than or equal to num.
}
counter++;
}
console.log(arrayOfPrimeNumbers);
}
sumPrimes(10);
It seems like the code leads to some kind of infinite loop. I’d be most grateful if someone can point me in the right direction, thanks in advance.