Tell us what’s happening:
Describe your issue in detail here.
Hi everyone - I am working on the sum of all primes algorithm and it works for numbers up to 27 - but at 27 it breaks as it thinks 27 is a prime number! I am confused please help!
**Your code so far**
function sumPrimes(num) {
//find all the numbers in the range
let range = [];
for (let i = 2; i <= num; i++){
range.push(i);
}
//iterate through each number in the range and check if is divisible by anything
for (let j = 0; j < range.length; j++){
for (let k = 2; k < num; k++){
if (range[j] % k === 0){
if(range[j] != k){
range.splice(j, 1)
}
}
}
}
return range.reduce((a, b) => a + b, 0);
}
console.log(sumPrimes(27));
**Your browser information:**
User Agent is: Mozilla/5.0 (X11; CrOS x86_64 14388.61.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.107 Safari/537.36
splicing out array entries as you iterate over the array is dangerous:
function sumPrimes(num) {
//find all the numbers in the range
let range = [];
for (let i = 2; i <= num; i++) {
range.push(i);
}
//iterate through each number in the range and check if is divisible by anything
for (let j = 0; j < range.length; j++) {
console.log("checking:", range[j]);
for (let k = 2; k < num; k++) {
if (range[j] % k === 0) {
console.log("" + range[j] + " is divisible by " + k);
if (range[j] != k) {
range.splice(j, 1);
}
console.log("range is now:", range);
}
}
}
console.log("final range:", range);
return range.reduce((a, b) => a + b, 0);
}
console.log(sumPrimes(27));
Side note: this approach will fail the big tests because it is a bit too slow. I’d ask yourself
do you need to build the range?
do you need to keep checking values of k if you found one that divides into your number?
This is one that a lot of people want to use an array for. There is a really fast algorithm that uses an array, but it’s different than the approach you took.
In general, when making an array, ask yourself how many times you will use the data inside the array. If it’s only once (like to sum it), then you probably don’t want an array.