DEV Community

Discussion on: JavaScript Algorithm: Sum of All Primes

Collapse
 
lexlohr profile image
Alex Lohr • Edited

This is a (pun intended) prime example of recursion allowing a more concise solution:


const sumPrime = (max, current = 2, divisor = 2, sum = 0) =>
  // reached end of recursion, return sum
  current > max
  ? sum
  // found prime, add to sum and run with next value
  : current % divisor === 0
  ? sumPrime(max, current + 1, 2, sum + current)
  // value is is not a prime, run with next value
  : divisor >= current / 2
  ? sumPrime(max, current + 1, 2, sum)
  // otherwise increase divisor
  : sumPrime(max, current, divisor + 1, sum);
Enter fullscreen mode Exit fullscreen mode

Your solution is valid, just the use of an array to sum up the primes is superfluous.