Back to Freecodecamp

Build a Prime Number Sum Calculator

curriculum/challenges/english/blocks/lab-prime-number-sum-calculator/a3bfc1673c0526e06d3ac698.md

latest1.4 KB
Original Source

--description--

In this lab, you will build a calculator that takes a number and returns the sum of all prime numbers that are less than or equal to that number.

Objective: Fulfill the user stories below and get all the tests to pass to complete the lab.

User Stories:

  1. You should have a sumPrimes function that accepts a number as an argument.
  2. The sumPrimes function should return the sum of all prime numbers less than or equal to the provided number.
  3. If the input number is less than 2, the function should return 0.

--hints--

You should have a sumPrimes function.

js
assert.isFunction(sumPrimes);

sumPrimes(10) should return 17.

js
assert.strictEqual(sumPrimes(10), 17);

sumPrimes(5) should return 10.

js
assert.strictEqual(sumPrimes(5), 10);

sumPrimes(2) should return 2.

js
assert.strictEqual(sumPrimes(2), 2);

sumPrimes(0) should return 0.

js
assert.strictEqual(sumPrimes(0), 0);

sumPrimes(977) should return 73156.

js
assert.strictEqual(sumPrimes(977), 73156);

--seed--

--seed-contents--

js

--solutions--

js
function sumPrimes(num) {
  function isPrime(n) {
    if (n < 2) return false;
    for (let i = 2; i <= Math.sqrt(n); i++) {
      if (n % i === 0) {
        return false;
      }
    }
    return true;
  }

  let sum = 0;

  for (let i = 2; i <= num; i++) {
    if (isPrime(i)) {
      sum += i;
    }
  }
  return sum;
}