Skip to content

Instantly share code, notes, and snippets.

@jcolebot
Created May 2, 2022 19:52
Show Gist options
  • Select an option

  • Save jcolebot/20f9e80593fa28da5fbfb0fa8bd84911 to your computer and use it in GitHub Desktop.

Select an option

Save jcolebot/20f9e80593fa28da5fbfb0fa8bd84911 to your computer and use it in GitHub Desktop.
freeCodeCamp: Sum All Primes Solution
// A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself.
// For example, 2 is a prime number because it is only divisible by 1 and 2.
// In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
// Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
function sumPrimes(num) {
let primeArr = [];
for(let i = 2; i <= num; i++) {
if(primeArr.every((prime) => i % prime !== 0))
primeArr.push(i);
}
return primeArr.reduce((sum, prime) => sum + prime, 0);
}
// Another Solution Using JS Math Object
function sumPrimes(num) {
// Helper function to check primality
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0)
return false;
}
return true;
}
// Check all numbers for primality
let sum = 0;
for (let i = 2; i <= num; i++) {
if (isPrime(i))
sum += i;
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment