# freeCodeCamp Challenge Guide: Sum All Primes

freeCodeCamp Challenge Guide: Sum All Primes
0

Hello everyone, I want to share my solution:

``````function checkPrime(number) {
if (number === 0 || number === 1) return false;
for(var i = 2; i <= number; i++) {
if(number % i === 0 && number != i) {
return false;
}
}
return true;
}

function sumPrimes(num) {
var result = 0;
for(var number = 0; number <= num; number++) {
if(checkPrime(number)) {
result += number;
}
}
return result;
}
``````
1 Like

Another kind-of-simple solution:

``````function sumPrimes(num) {
var primes = [];
var sum = 0;
for (var i = 2; i <= num; i++) {
var checkForPrime = true;
for (var j = 2; j < i; j++) {
if (i % j === 0) {
checkForPrime = false;
break;
}
}
sum += checkForPrime ? i : 0;
}
return sum;
}

sumPrimes(10);``````

A one-liner solution using regex.

``````function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str.replace(/[\s_]?((?!^)[A-Z])/g, '-\$1').split(/\s/).join("-").toLowerCase();
}

spinalCase('Teletubbies say Eh-oh');
``````

Explanation: The regex replaces spaces with a ā-ā. The [A-Z] part is enclosed in parentheses to form a capturing group, in order to then be injected after the ā-ā using the matched Capital letter. The (?!) is a non-capturing group to ignore capital letters at the beginning of the stringā¦ the /g at the end is to apply this regex on all matches in the string, rather than just once.

Then the split and join are there to replace any remaining spaces with dashes (this is a workaroundā¦ couldnāt figure out a way to incorporate it in the single regex)

Think mine is a bit complicated, but it works:

``````function sumPrimes(num) {

// Check if a given number is a prime number
var isPrime = function(x) {
for (var i = 2; i <= Math.sqrt(x); i++) {
if (x % i === 0) {
return false;
}
}
return true;
};

// holds all prime numbers

// performs check for each value from 2 up to and including the passed num
for (var i = 2; i <= num; i++) {
if (isPrime(i)) {
}
}

// sums all prime numbers and returns them
return a + b;
});

return sum;
}

sumPrimes(10);``````

My take was quite simple for me though I have poor math capabilities. It was easy due to the simple and clever algorithm description from here http://mathforum.org/dr.math/faq/faq.prime.num.html, see under āThe Sieve of Eratosthenesā heading.

What I did is just straigntforwardly followed algorithm explanation translating from English into JavaScript. After I created the `sieve` array from 2 to `num` I wrote one `filter` loop to remove all numbers divisible by 2 from the `sieve`. Then wrote second `filter` loop to remove all divisible by 3.

I could continue to copy āfilterā loops and replace 3 with 4, 5, 6, 7 etc. till I reached `num`. But instead obviously I just replaced all repeating `filter` loops with the one wrapped in plain `for` loop incrementing form 2 to ānumā. Each loop engages its `filter` loop that removes all the numbers that are divisible by the `for` wrapper count from the `sieve` array, which is what the algorithm description suggests.

I like my solution.

``````function sumPrimes(num) {
var sieve = [];
for (var i = 1; i < num; i++) {
sieve[i] = i + 1;
}
for (var k = 2; k < num; k++) {
sieve = sieve.filter(function(elt) {
return (elt === k) || (elt % k !== 0);
});
}
return sieve.reduce(function(acc, elt) {
return acc + elt;
});
}
``````
1 Like

The new version where I deleted inefficiencies in the `for` wrapper uselessly iterating with counts which had been already deleted from `sieve` before. Now the function precisely follows Eratosthenesās algorithm and iterates through dinamically changed `sieve` array using its own values.

``````    function sumPrimes(num) {
var sieve = [];
for (var i = 0; i < num - 1; i++) {
sieve[i] = i + 2;
}
for (var k = 0; k < sieve.length - 1; k++) {
// debugger;
sieve = sieve.filter(function(elt) {
return (elt === sieve[k]) || (elt % sieve[k] !== 0);
});
}
return sieve.reduce(function(acc, elt) {
return acc + elt;
});
}
``````

Nice approach!! ā¦ Mine is kinda basic

``````function sumPrimes(num) {

var sm = 0;
var objN = {}

for(var x=1; x<=num; x++){
var ct = 0;
for(var j = 1; j <= x; j++){
if(x % j === 0){
ct++;
}
objN[x] = ct;
}
}

for(var m in objN){
if(objN[m] > 1 && objN[m] <= 2){
sm+= parseInt(m);
}
}

return sm;
}

sumPrimes(977);
``````

Thanks RazorBent Basic is usually good for both speed and readability.

I used to like the approaach as well. Though I would like to share that as soon as I tasted well the JS Array methods I liked them equally as much as a good old `for` loop.

My rule of thumb whether to use an Array method or not is if I want to return the mutated value from my operation over an array or not. If former I use appropriate Array method. Otherwise if the result of the loop is somewhere outside the array being operated on, I use `for` (or say `while`).

Based my work on a paragraph hereā¦
This is the first time Iāve felt compelled to post my solution. Since Iām following tutorials they are usually not significantly different to be covering any new territory, but I got out in the weeds on this one and some how still made it back, 233 lines laterā¦

``````//helper functions
function isItEven(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 1) {
return;
}
if (n === 2) {
return n;
}
if (n % 2 !== 0) {
console.log(n);
return n;
}
} //end of isItEven

function isItTHREED(n) {
//  [based my work off a paragraph here..](https://www.thoughtco.com/how-to-determine-number-is-prime-2312518)
if (n === 3) {
return n;
}
//  Try 3.  Take the number, and add the digits up, when those digits are divisible by 3, the number is not prime.
//          Take 2469, those digits add up to 21, and 21 is divisible by 3, therefore 2469 is not a prime number.
console.log("3s", n);
n = n.toString();
var digitONE = Number(n.charAt(0));
var digitTWO = Number(n.charAt(1));
var digitTHREE = Number(n.charAt(2));
var digitFOUR = Number(n.charAt(3));
console.log("digits", digitONE);
console.log("digits", digitTWO);
console.log("digits", digitTHREE);
console.log("digits", digitFOUR);
var testing = digitONE + digitTWO + digitTHREE + digitFOUR;
console.log(testing);
n = Number(n);
if (testing % 3 !== 0) {
return n;
}
} //end of isItTHREED

function isItFOURED(n) {
//  https://www.thoughtco.com/how-to-determine-number-is-prime-2312518
var fourTrap = [];
n = n.toString();
var digitLAST = Number(n.charAt(n.length));
var digitNEXTtoLast = Number(n.charAt(n.length - 1));
console.log("digits", digitLAST);
console.log("digits", digitNEXTtoLast);
var testing = digitLAST + digitNEXTtoLast;
console.log(testing);
n = Number(n);
if (testing % 4 === 0) {
fourTrap.push(n);
console.log("fourThrap", fourTrap);
}
if (testing % 4 !== 0) {
return n;
}
} //end of isItFOURED

function isItFIVED(n) {
if (n === 5) {
return n;
}
var fifthTrap = [];
var fifthLast = n.toString();
console.log(n);
var digitLAST = Number(fifthLast.charAt(fifthLast.length - 1));
var testing = digitLAST;
console.log("testLOG", testing);
n = Number(n);
if (testing === 5 || testing === 0) {
fifthTrap.push(n);
console.log("traptFIVE", fifthTrap);
}
if (testing !== 5 && testing !== 0) {
return n;
}
} //end of isItFIVED

function isItSeveneD(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 7) {
return n;
}
if (n % 7 !== 0) {
console.log(n);
return n;
}
} //end of isItSeveneD

function isItElevened(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 11) {
return n;
}
if (n % 11 !== 0) {
console.log(n);
return n;
}
} //end of isItElevened

function isIt13th(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 13) {
return n;
}
if (n % 13 !== 0) {
console.log(n);
return n;
}
} //end of isIt13th

function isIt17th(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 17) {
return n;
}
if (n % 17 !== 0) {
console.log(n);
return n;
}
} //end of isIt17th

function isIt19th(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 19) {
return n;
}
if (n % 19 !== 0) {
console.log(n);
return n;
}
} //end of isIt19th

function isIt23rd(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 23) {
return n;
}
if (n % 23 !== 0) {
console.log(n);
return n;
}
} //end of isIt23rd

function isIt29(n) {
//  Try 2: is an even number and it will be divisible by 2, therefore it is not prime.
if (n === 29) {
return n;
}
if (n % 29 !== 0) {
console.log(n);
return n;
}
} //end of isIt29

function isItThirtyONED(n) {
if (n === 31) {
return n;
}
if (n % 31 !== 0) {
console.log(n);
return n;
}
} //end of isItThirtyONED

function sumPrimes(num) {
var primes = [];
var i = 1;
while (i < num + 1) {
primes.push(i);
i++;
}
console.log("primes", primes);
primes = primes.filter(isItEven);

//  Try 3.  Take the number, and add the digits up, when those digits are divisible by 3, the number is not prime.
//          Take 2469, those digits add up to 21, and 21 is divisible by 3, therefore 2469 is not a prime number.
primes = primes.filter(isItTHREED);
console.log("isItTHREED", primes);

//  Try fours.
primes = primes.filter(isItFOURED);
console.log("isItFOURED", primes);

//  Try fives
primes = primes.filter(isItFIVED);
console.log(primes);

//  Try 7
primes = primes.filter(isItSeveneD);
console.log(primes);

//  Try 11
primes = primes.filter(isItElevened);
console.log(primes);

//  Try 13
primes = primes.filter(isIt13th);
console.log(primes);

//  Try 13
primes = primes.filter(isIt17th);
console.log(primes);

//  Try 19
primes = primes.filter(isIt19th);
console.log(primes);

//  Try 23
primes = primes.filter(isIt23rd);
console.log(primes);

//  Try 29
primes = primes.filter(isIt29);
console.log(primes);

//  Try 31
primes = primes.filter(isItThirtyONED);
console.log(primes);

//might extract the anounoum function.. may also use it to filter out evens?
var reducted = primes.reduce((total, amount) => total + amount);
num = Number(reducted);
//console.log(num);
return num;
} //sumPrimes

sumPrimes(10); // should return 17.
//sumPrimes(100); // should return 17.
//sumPrimes(977); // should return 73156.
//2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41``````
``````
function sumPrimes(num) {
//declare vars. One to store an array of prime numbers and another to store the sum of these numbers.
var primes = [];
var primeSum = 0;
//create a function to check for prime numbers
function isPrime(num) {
if(num < 2)
return false;
for (var i = 2; i < num; i++) {
if(num%i===0)
return false;
}
return true;
}
//increment through all numbers less than num and pass i to the function isPrime. If true, then push the number to the var primes.
for(var i = 0; i <= num; i++){
if(isPrime(i)) {
primes.push(i);
}
}
//Once the array of prime numbers has been created, iterate through this array and add all the numbers together and store in the var primeSum.
for (var j = 0; j < primes.length; j++){
primeSum += primes[j];
}
//return the var prime Sum.
return primeSum;
}

sumPrimes(977);

``````

A little tricky, but in the end I found this solution:

I believe this solution is more optimal than the advanced solution:

``````function sumPrimes(num) {
var sum = 0;
for(var i = 0; i <= num;i++){
if(IsPrime(i)){
sum += i;
}
}
return sum;
}

function IsPrime(n){
if(n <= 1) return false;
for(var j = 2; Math.pow(j,2) <= n;j++){
if(n % j === 0) {
return false;
}
}
return true;
}
``````

Time complexity: O(n * sqrt(n))
Space Complexity: O(1)

1 Like

I agree. I had a similar solution:

``````function sumPrimes(num) {
var sum = 0;

function isPrime(x) {
var factors = [];
for (var i = 1; i <= x; i++) {
if (x % i == 0) {
factors.push(i);
}
}
if (factors.length == 2) {
return true;
} else {
return false;
}
}

for (var j = 1; j <= num; j++) {
if (isPrime(j)) {
sum += j;
}
}

return sum;
}

sumPrimes(10);``````

A simple one:

``````function sumPrimes(num) {
if(num < 2) return 0;
//taking 2 since it is only even prime number --> will save one cycle of loop
var sum = 2;
var flag = false;
for(var i = 3; i <= num;) {
flag = checkForPrime(i);
if (flag === false) {
sum += i;
}
// to check only odd numbers
i += 2;
}
return sum;
}

function checkForPrime(num) {
// a nuber has all the factors within it's sqare root
var sqrt = Math.sqrt(num);
var flag = false;
for(var i = 3; i <= sqrt;) {
if(num % i === 0) flag = true;
i = i + 2;
}
return flag;
}

``````

Here is my solution, but I canāt fix why 2 didnāt appears as prime number.
I use this algorithm to check if the number is prime or not:

``````function sumPrimes(num) {
var arr = [];
var sum = 2; // I can't fix why 2 didn't appears as prime number in my solution
for (var i=0;i<=num;i++) {
arr.push(i);
}
for (i=0;i<arr.length;i++) {
var sqrAnValue = Math.ceil(Math.sqrt(arr[i]));
for(var j=2;j<=sqrAnValue;j++) {
if(arr[i]%j === 0) {
break;
} else if (arr[i]%j !== 0 && j == sqrAnValue)  {
sum += arr[i];
}
}
}
return sum;``````

## Basic Code Solution:

``````function sumPrimes(num) {
var sum = 0;
var divider;

for (var i = 2; i <= num; i++) {
divider = 2;
while (i % divider !== 0) {
divider++;
}
if (i === divider) {
sum += i;
}
}

return sum;
}
``````
2 Likes

Basic solution, but it works!

``````function sumPrimes(num) {
var cont = 0;
var res = 0;
for(var i = 2; i <= num; i++){
for(var j = 1; j <= i; j++){
if(i%j === 0){
cont++;
}
}
if(cont === 2){
res += i;
}
cont = 0;
}
return res;
}

sumPrimes(5);``````
1 Like
``````function sumPrimes(num) {

var arr = [];

function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i==0)
return false;
}
return true;
}

for(var i=0;i<=num;i++){
if (isPrime(i)){
arr.push(i);
}
}

return arr.reduce(function(sum, value) {
return sum + value;
}, 0);

}

sumPrimes(977);``````

To determine if a number n is prime, you only need to try dividing n by primes, since all the composites (non-primes) are multiples of primes you already tested.

Also, once the prime p you are testing exceeds the square root of n, and n % p has always had a remainder, you donāt need to go any further ā p (or higher) would have to be multiplied by a lower value to possibly equal n, and youāve already tested all the possible lower values! At this point, you know that n is prime.

``````function sumPrimes(num) {
var sum = 2;
var p = [2];

for (var n = 3; n <= num; n++) {
for (var i = 0; i < p.length; i++) {
if (n % p[i] === 0) break;
if (n / p[i] < p[i]) {
sum += n;
p.push(n);
break;
}
}
}
return sum;
}
``````
2 Likes