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

pull/34297/head
Aditya 2018-11-11 20:20:08 +05:30 committed by Valeriy
parent 231dad3c28
commit 9e688056ef
1 changed files with 12 additions and 31 deletions

View File

@ -49,49 +49,30 @@ primeSummation(2000000);
</div>
</section>
## Solution
<section id='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;
}
```