Badly implemented sieve of Eratosthenes
Time limit1sMemory limit512 MB
Count how many times the inner statement runs in a nested loop where the outer index i goes from 1 to n and the inner step is i, for n up to 10^9.
- Level
Easy3 of 10
- Topics
- Math, Number theory, Implementation
- Solved
- No attempts yet
Problem
Seongwon implemented the sieve of Eratosthenes in C++ from memory after class. Hyeongseok, sitting next to him, said the code was wrong, and the two decided to count how many times line 6 runs. Given , compute that count.
The code is as follows.
int n;
cin >> n; // read n
int* sieve = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j += i) {
sieve[j] += 1; // line 6
}
}
The outer loop runs from to . The inner loop starts at and adds while does not exceed . Line 6 is the body of the inner loop, and the task is its total execution count.
Input
The first line contains a natural number with .
Output
Print the total number of executions of line 6 on the first line.