Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the sieve array with true values.
DSA C++
bool sieve[n+1]; for (int i = 0; i <= n; i++) { sieve[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing sieve with false will mark all numbers as non-prime from the start.
✗ Incorrect
The sieve array should be initialized with true to mark all numbers as potentially prime initially.
2fill in blank
mediumComplete the code to start crossing out multiples from the square of the current prime.
DSA C++
for (int j = [1]; j <= n; j += i) { sieve[j] = false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 2*i crosses out multiples twice.
Starting from i+1 is incorrect because it may not be a multiple.
✗ Incorrect
Crossing out multiples starts from i squared because smaller multiples were already handled by smaller primes.
3fill in blank
hardFix the error in the loop condition to only check up to the square root of n.
DSA C++
for (int i = 2; i <= [1]; i++) { if (sieve[i]) { // cross out multiples } }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking up to n is inefficient and unnecessary.
Using n/2 is arbitrary and not optimal.
✗ Incorrect
We only need to check primes up to the square root of n because larger factors are covered by smaller ones.
4fill in blank
hardFill both blanks to print all prime numbers after sieve completion.
DSA C++
for (int i = 2; i <= n; i++) { if (sieve[[1]]) { std::cout << [2] << " "; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using n or i+1 instead of i causes wrong output or errors.
Using sieve[i] as a print value prints true/false instead of the number.
✗ Incorrect
We check sieve[i] to see if i is prime and print i itself.
5fill in blank
hardFill all three blanks to complete the sieve function that returns a vector of primes.
DSA C++
std::vector<int> sieveOfEratosthenes(int n) {
std::vector<int> primes;
bool sieve[n+1];
for (int i = 0; i <= n; i++) {
sieve[i] = [1];
}
for (int i = 2; i <= [2]; i++) {
if (sieve[i]) {
for (int j = i * i; j <= n; j += i) {
sieve[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (sieve[i]) {
primes.push_back([3]);
}
}
return primes;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing sieve with false causes no primes to be found.
Looping up to n instead of sqrt(n) is inefficient.
Pushing back sieve[i] instead of i adds boolean values.
✗ Incorrect
Initialize sieve with true, loop up to sqrt(n), and add i to primes if sieve[i] is true.
