fix(curriculum): Problem 10 added optimized code (#31066)
This commit is contained in:
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// At this point x must be prime
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
let sum = 2;
|
||||||
// For every odd integer, add it to the array if it is prime
|
for (let i = 3; i < n; i += 2){
|
||||||
for (let x = 3; x < n; x += 2) {
|
if (nums[i] !== 0){
|
||||||
if (isPrime(x, primes)) {
|
sum += nums[i];
|
||||||
if (x > n) {
|
for (let j = i*i; j < n; j += i){
|
||||||
return result;
|
nums[j] = 0;
|
||||||
} else {
|
|
||||||
result += x;
|
|
||||||
primes.push(x);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return sum;
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user