Answer the question
In order to leave comments, you need to log in
How to make an algorithm for calculating the sum of prime numbers according to the principle of Sita Erastofen?
Good day. I wrote a code that calculates the sum of prime numbers from zero to a given number. But everything works fine for small numbers, when I set the number 977 it should be 73156 and I have 108618. Who can help?
function sumPrimes(num) {
let numArr = [2];
let delLength3 = [];
let delLength5 = [];
let delLength7 = [];
for (let i = 4; i <= num; i = i + 3) {
delLength3.push(i);
}
for (let i = 5; i <= num; i = i + 5) {
delLength5.push(i);
}
for (let i = 14; i <= num; i = i + 7) {
delLength7.push(i);
}
for (let i = 2; i <= num; i++) {
if (i % 2 !== 0) {
numArr.push(i);
}
}
delLength3.map(el => {
numArr[el] = "x";
});
delLength5.map(el => {
numArr[el] = "x";
});
delLength7.map(el => {
console.log(el)
let index = numArr.indexOf(el)
if (index >= 0) {
numArr[index] = 'x'
}
});
let newArr = numArr.filter(el => {
if (typeof el === "number") {
return el;
}
});
let sumArr = newArr.reduce((a, b) => {
return a + b;
});
console.log(sumArr);
return sumArr;
}
sumPrimes(977);
Answer the question
In order to leave comments, you need to log in
Many questions about the code
1) Why is it starting from 4 and not from 3?
2) Why is it starting from 14, and not from 7
3) Firstly, you already have a deuce in the array, and secondly, why the condition if you can just i + = 2?
for (let i = 2; i <= num; i++) {
if (i % 2 !== 0) {
numArr.push(i);
}
}
const simpleNumbersSum = max => {
const arr = new Array(max + 1)
let sum = 1 + 2; //Или просто 2, если единицу не учитываем
for (let i = 3; i <= max; i+=2) {
if (!arr[i]) {
sum+=i;
for (let j = i * i; j <= max; j+=i*2) {
arr[j] = true;
}
}
}
return sum
}
console.log(simpleNumbersSum(977))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question