Computer >> Computer tutorials >  >> Programming >> Javascript

Sum of all prime numbers in JavaScript


We are required to write a JavaScript function that takes in a number as the only argument. The function should find and return the sum of all the prime numbers that are smaller than n.

For example −

If n = 10, then the output should be 17, because the prime numbers upto 10 are 2, 3, 5, 7, whose sum is 17

Example

The code for this will be −

const isPrime = (num) => {
   let x = Math.floor(Math.sqrt(num));
   let j = x;
   while (j >= 2) {
      if (num % j === 0) {
         return false;
      }
      j−−;
   }
   return true;
};
const sumOfPrimes = (num = 10) => {
   let iter = num;
   let sum = 0;
   while (iter >= 2) {
      if (isPrime(iter) === true) {
         sum += iter;
      }
      iter−−;
   }
   return sum;
};
console.log(sumOfPrimes(14));
console.log(sumOfPrimes(10));

Output

And the output in the console will be −

41
17
1060