fix(curriculum): Problem 10 added optimized code (#31066)

This commit is contained in:
Aditya
2018-11-11 20:20:08 +05:30
committed by Valeriy
parent 231dad3c28
commit 9e688056ef

View File

@ -49,49 +49,30 @@ primeSummation(2000000);
</div> </div>
</section> </section>
## Solution ## Solution
<section id='solution'> <section id='solution'>
```js ```js
//noprotect //noprotect
function primeSummation(n) { function primeSummation(n) {
// Initialise an array containing only prime numbers if (n < 3) { return 0 };
let primes = [2]; let nums = [0, 0, 2];
let result = 2; for (let i = 3; i < n; i += 2){
nums.push(i);
function isPrime(y, primes) { nums.push(0);
// 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;
} }
} let sum = 2;
for (let i = 3; i < n; i += 2){
// At this point x must be prime if (nums[i] !== 0){
return true; sum += nums[i];
} for (let j = i*i; j < n; j += i){
nums[j] = 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);
} }
} }
} }
return sum;
return result;
} }
``` ```