Files
freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-10-summation-of-primes.english.md
Kristofer Koishigawa 6cfd0fc503 fix: improve Project Euler descriptions, challenge seeds, and test cases (#38016)
* fix: improve Project Euler descriptions and test case

Improve formatting of Project Euler test descriptions. Also add poker hands array and new test case for problem 54

* feat: add typeof tests and gave functions proper names for first 100 challenges

* fix: continue fixing test descriptions and adding "before test" sections

* fix: address review comments

* fix: adjust grids in 18 and 67 and fix some text that reference files rather than the given arrays

* fix: implement bug fixes and improvements from review

* fix: remove console.log statements from seed and solution
2020-02-28 06:39:47 -06:00

1.6 KiB

id, challengeType, title, forumTopicId
id challengeType title forumTopicId
5900f3761000cf542c50fe89 5 Problem 10: Summation of primes 301723

Description

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below n.

Instructions

Tests

tests:
  - text: <code>primeSummation(17)</code> should return a number.
    testString: assert(typeof primeSummation(17) === 'number');
  - text: <code>primeSummation(17)</code> should return 41.
    testString: assert.strictEqual(primeSummation(17), 41);
  - text: <code>primeSummation(2001)</code> should return 277050.
    testString: assert.strictEqual(primeSummation(2001), 277050);
  - text: <code>primeSummation(140759)</code> should return 873608362.
    testString: assert.strictEqual(primeSummation(140759), 873608362);
  - text: <code>primeSummation(2000000)</code> should return 142913828922.
    testString: assert.strictEqual(primeSummation(2000000), 142913828922);

Challenge Seed

function primeSummation(n) {
  // Good luck!
  return true;
}

primeSummation(2000000);

Solution

//noprotect
function primeSummation(n) {
  if (n < 3) { return 0 };
  let nums = [0, 0, 2];
  for (let i = 3; i < n; i += 2){
    nums.push(i);
    nums.push(0);
  }
  let sum = 2;
  for (let i = 3; i < n; i += 2){
    if (nums[i] !== 0){
      sum += nums[i];
      for (let j = i*i; j < n; j += i){
        nums[j] = 0;
      }
    }
  }
  return sum;
}