Background Information:
So am trying to calculate all the prime numbers inside a number, and then sum them up. sumPrimes(10)
should return 17
because 2 + 3 + 5 + 7 = 17
.
The challenge is here --> https://www.freecodecamp.org/challenges/sum-all-primes
I added some console.log
's in just to show whats happening.
My Approach:
My approach to doing this was trying to replicate this tutorial here but in code: https://youtu.be/FBbHzy7v2Kg?t=67
What i tried with my code was to separate the number into a array from 2, to what ever your number is (1 isn't prime). 10
would look like [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
. Then i use another for
loop with i
to pick a number out of that previous array arr
, add it to prime
, and then remove every multiple of that number from the array (arr
) using a separate loop. When i go back to go get another number, we already know its a prime.
The rest of this is if you don't understand.
Example:
The first number of that array is 2. So i add 2 to prime
.
prime's current value:
2
And then filter out any multiple. Since i am counting by the number itself in my j
loop, i already know any number is a multiple. It also removes my already prime number from the array along with all its multiple's so it would never be undefined.
arr's current value (hopefully):
[ 3, 5, 7, 9]
etc (continues on with 3, 5, and then 7).
Whats going wrong?
Its not removing all the multiples. I am using splice
, and i don't think its cutting out that number correctly. Help?
Please don't just give me some ES6 answer and walk away. I want to stick with my (well the video's) idea. I don't care how short your answer is, just whats wrong with mine.
The repl --> https://repl.it/@John_Nicole/prime
function sumPrimes(num) {
var prime = 0;
var arr = [];
for (let i = 2; i <= num; i++) {
arr.push(i);
} // turns into array
console.log(arr)
for (let i = 0; i < arr.length; i++) {
var number = arr[i];
console.log("Prime: "+prime+"+"+number)
prime+=number
for (var j = number; j <= arr.length; j+=number) {
arr.splice(j)
} // j
} // i
return "Final result: "+prime;
}
sumPrimes(10);
Thanks in advance :D