Need Help With My 'Sum All Primes' Code

Need Help With My 'Sum All Primes' Code
0

#1

**

!SPOILERS AHOY!

**

This is in regards to the ‘Sum All Primes’ intermediate algorithm, which asks you to write a function that sums all primes up to the given number.

My code looks like it’s returning the correct sums for all the primes that I’ve fed to it… except for the final test number, which is 977!

Could anyone take a look and explain to me why my code seems to work only up to a certain point? Thanks in advance!

function sumPrimes(num) {
var sum = 5;
var current = 3;
while(current < num){
current+=1;
if(current%2!==0 && current%3!==0){
sum+=current;
}
}
return sum;
}


#2

Also, this is a recurring problem for me with “Sum of All Odd Fibonacci” and “Smallest Common Multiple”–my code for both of these algorithms works with all numbers up to the final test. It’s driving me insane. Partly with curiosity. Mostly with frustration.


#3

Your current code works because you are hardcoding some values that makes it work with sumPrime(10)

For starter, you should ask yourself why you needed “sum” to have a value of 5 by default. This is a pointer to your current problem.

Also, a prime number is a number that can only be divided by 1, and itself.

You could approach this problem differently, think of a way to iterate through all numbers and comparing each of them together, This could be done with a nested for loop.


#4

You seem to think 25 is prime. At least according to your code :~)

Your algorithm takes 25 and since it’s not divisible by 2 nor by 3, it adds it happily to the sum of primes. There are an infinite amount of other numbers that are not divisible by 2 and 3, yet are not prime. Try it out in the console of you browser and add a console.log(current); for every ‘prime’ it finds.I think you’ll quickly agree that your approach is too simple.

There are very very old but efficient algorithms for finding primes, check out Wikipedia. If you find that too complex (it probably looks a bit daunting at first, but really isn’t), you can try to generalize your algorithm and brute force the result.

Also I’d suggest you use more than one function to separate concerns, maybe one for finding primes and one for summing them up? It’s easier to think about problems if you can split them up into smaller, less complex ones.


#5

Thanks for the input, guys! These math-based algorithms were pretty sharp detour from my usual practice, so I think a lot of it is just getting used to the thinking.