sum of all prime numbers below a given number in javascript code example
Example 1: sum prime numbers javascript
function sumPrimes(num) {
let i = 1;
let sum = 0;
while (i <= num) {
if (isPrime(i)) {
sum += i;
}
i++;
}
return sum;
}
function isPrime(x) {
for (let i = 2; i < x; i++) {
if (x % i === 0) return false;
}
return x !== 1 && x !== 0;
}
sumPrimes(10);
Example 2: sum of all primes below 2 javascript
function sumPrimes(num) {
let sum = 0;
const isPrime = n => {
for (let i = 2; i < n; i++)
if (n % i === 0) return false;
return n !== 1;
}
for (i = 2; i <= num; i++) {
if (isPrime(i)) {
sum += i;
console.log(i);
console.log(isPrime(i));
}
}
console.log(sum);
return sum;
}
sumPrimes(10);