Hello, can somebody make any sense of what’s going on here? It seems that my code is able to…track?..prime numbers but only up unto about the 500-something range or so. And then it mysteriously seems to start including non-prime numbers. I “console.log”-ed in case that helps. Thanks and sorry for the sloppy code!
function sumPrimes(num) {
let numArr = [];
for (let i = 2; i <= num; i++){
numArr.push(i);
}
let subtractArr = [];
for (let i = 0; i < numArr.length; i++){
let varInd = numArr[i];
for (let j = 0; j < numArr.length;j++){
let varInd2 = numArr[j];
if ((varInd != varInd2) && ((varInd % varInd2) === 0) && (subtractArr.indexOf(varInd) < 0)){
subtractArr.push(varInd);
}
}
}
let finalArr = numArr.filter((x)=> subtractArr.indexOf(x) < 0 );
console.log(finalArr)
function arrTot (total, num){
return total + num;
}
return finalArr.reduce(arrTot);
}
sumPrimes(977);
Your solution passes for me.
In general, if a solution doesn’t pass for the big numbers, it means that the algorithm isn’t efficient enough and FCC’s test is timing out (it keeps running, just gives wrong answers). Since the code is running in our browsers, it makes sense that this would vary among our computers.
2 Likes
Thanks for the response, Kevin! I assumed something similar after not getting an immediate response last night–tried the code in Safari and it passed immediately.
In your opinion, do you think it’s wise to refactor my work until it passes in Chrome?
Its never a bad idea to benchmark your code. Unless you’re facing a deadline…
In the case of this particular task, I really think that taking a look at the Sieve of Eratosthenes is a great way to improve efficiency.
I’ll definitely take a look at that! Being kind of stubborn, I wanted to try to solve it “on my own” initially. But, just as in the case of your profile description, I keep hearing about the beauties of “efficient code” and it seems worthy of aspiring towards. Again, I appreciate the time taken!
The beauty of that solution is, its simply an algorithm. It isn’t the code. You still have to write that baby all your own self, it just gets you thinking along a different tack.
1 Like
That depends - Is your goal to pass the test or learn? Look at it this way - If you had a job interview, a more efficient solution is much more likely to get you the job.
2 Likes
Excellent advice–it seems this field requires overcoming any tendencies toward laziness! Thanks for the response!