From 9e688056efbcb434a463bf07a3e43db64ccddbb0 Mon Sep 17 00:00:00 2001 From: Aditya Date: Sun, 11 Nov 2018 20:20:08 +0530 Subject: [PATCH] fix(curriculum): Problem 10 added optimized code (#31066) --- .../problem-10-summation-of-primes.english.md | 43 ++++++------------- 1 file changed, 12 insertions(+), 31 deletions(-) diff --git a/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-10-summation-of-primes.english.md b/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-10-summation-of-primes.english.md index 8317feedc99..3b0bc83eb9c 100644 --- a/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-10-summation-of-primes.english.md +++ b/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-10-summation-of-primes.english.md @@ -49,49 +49,30 @@ primeSummation(2000000); - - ## Solution
- ```js //noprotect function primeSummation(n) { - // Initialise an array containing only prime numbers - let primes = [2]; - let result = 2; - - function isPrime(y, primes) { - // Find sqrt(y) - const sqrt = Math.floor(Math.sqrt(y)); - - // Divide y by each applicable prime, return false if any of them divide y - for (let i = 0; i < primes.length && primes[i] <= sqrt; i++) { - if (y % primes[i] === 0) { - return false; - } - } - - // At this point x must be prime - return true; + if (n < 3) { return 0 }; + let nums = [0, 0, 2]; + for (let i = 3; i < n; i += 2){ + nums.push(i); + nums.push(0); } - - // For every odd integer, add it to the array if it is prime - for (let x = 3; x < n; x += 2) { - if (isPrime(x, primes)) { - if (x > n) { - return result; - } else { - result += x; - primes.push(x); + 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 result; + return sum; } ```