Answer the question
In order to leave comments, you need to log in
How to understand the solution of the problem in JS?
I am studying a tutorial on learn.javascript.ru
task:
Create a list of consecutive numbers from 2 to n: 2, 3, 4, ..., n.
Let p=2, this is the first prime number.
Cross out all subsequent numbers in the list with a difference of p, i.e. 2p, 3p, 4p, etc. In the case of p=2 it would be 4,6,8....
Change the value of p to the first uncrossed number after p.
Repeat steps 3-4 until p2 < n.
All remaining uncrossed numbers are prime.
Came to arrays. I solve problems at the end ... I could not solve one of them and looked at the solution. Started to disassemble. I understood everything, but the moment when the sum of uncrossed numbers is considered is not clear. As I understand it, at the end it is not the sum of the numbers that is considered, but their number. Explain why the sum of numbers is still considered.
var arr = [];
for (var i = 2; i < 100; i++) {
arr[i] = true
}
var p = 2;
do {
for (i = 2 * p; i < 100; i = i + p) {
arr[i] = false;
}
for (i = p + 1; i < 100; i++) {
if (arr[i]) break;
}
p = i;
} while (p * p < 100);
var sum = 0;
for (i = 0; i < arr.length; i++) {
if (arr[i]) {
sum += i;
}
}
console.log(sum);
Answer the question
In order to leave comments, you need to log in
Here are the comments :)
var arr = [];
//Заполним массив
//изначально примем, что все числа от 2 до 100 - простые
//обратите внимание, что наши числа хранятся в индексе массива, а не в значении.
//в значении хранится статус, true - простое, false - не простое.
for (var i = 2; i < 100; i++) {
arr[i] = true
}
var p = 2; // первое простое число
//начинаем отсеивать все не простые числа
do {
//"зачеркиваем" числа по правилу в задаче - отсеиваем не простые числа с шагом в p
for (i = 2 * p; i < 100; i = i + p) {
arr[i] = false;
}
//ищем следующее незачеркнутое число
for (i = p + 1; i < 100; i++) {
if (arr[i]) break;
}
p = i;
} while (p * p < 100);
//тут у нас уже сформирован массив, index=>value, где index - наши числа от 2 до 99, а value - флаг, простое ли у нас число (true) в index или нет (false).
var sum = 0;
//соответственно, мы считаем сумму индексов массива, в которых у нас записаны простые числа
for (i = 0; i < arr.length; i++) {
//проверим, простое ли число. если простое - суммируем.
if (arr[i]) {
sum += i;
}
}
console.log(sum);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question