Challenge - 5 Problems
Sieve Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Sieve for n=10
What is the output list of primes after running the Sieve of Eratosthenes for n=10?
DSA Go
func sieve(n int) []int { primes := make([]bool, n+1) for i := 2; i <= n; i++ { primes[i] = true } for p := 2; p*p <= n; p++ { if primes[p] { for i := p * p; i <= n; i += p { primes[i] = false } } } var result []int for i := 2; i <= n; i++ { if primes[i] { result = append(result, i) } } return result } fmt.Println(sieve(10))
Attempts:
2 left
💡 Hint
Remember primes are numbers greater than 1 with no divisors other than 1 and themselves.
✗ Incorrect
The sieve marks multiples of each prime starting from its square as not prime. For n=10, primes are 2, 3, 5, and 7 only.
❓ Predict Output
intermediateCount of primes up to 20
How many prime numbers are found by the sieve for n=20?
DSA Go
func sieveCount(n int) int { primes := make([]bool, n+1) for i := 2; i <= n; i++ { primes[i] = true } for p := 2; p*p <= n; p++ { if primes[p] { for i := p * p; i <= n; i += p { primes[i] = false } } } count := 0 for i := 2; i <= n; i++ { if primes[i] { count++ } } return count } fmt.Println(sieveCount(20))
Attempts:
2 left
💡 Hint
List primes up to 20: 2,3,5,7,11,13,17,19
✗ Incorrect
There are exactly 8 primes less than or equal to 20.
🔧 Debug
advancedIdentify the error in sieve implementation
What error does this code produce when running sieve(10)?
DSA Go
func sieve(n int) []int { primes := make([]bool, n) for i := 2; i <= n; i++ { primes[i] = true } for p := 2; p*p <= n; p++ { if primes[p] { for i := p * p; i <= n; i += p { primes[i] = false } } } var result []int for i := 2; i <= n; i++ { if primes[i] { result = append(result, i) } } return result }
Attempts:
2 left
💡 Hint
Check the size of the boolean slice and the indices used.
✗ Incorrect
The slice primes has length n, but code accesses primes[n], which is out of range causing runtime panic.
🧠 Conceptual
advancedWhy start marking multiples from p*p?
In the Sieve of Eratosthenes, why do we start marking multiples of a prime p from p*p instead of 2*p?
Attempts:
2 left
💡 Hint
Think about when multiples get marked in earlier steps.
✗ Incorrect
Multiples less than p*p have already been marked by smaller primes, so starting at p*p avoids redundant work.
🚀 Application
expertFind sum of primes up to 50 using sieve
What is the sum of all prime numbers up to 50 found by the Sieve of Eratosthenes?
DSA Go
func sieveSum(n int) int { primes := make([]bool, n+1) for i := 2; i <= n; i++ { primes[i] = true } for p := 2; p*p <= n; p++ { if primes[p] { for i := p * p; i <= n; i += p { primes[i] = false } } } sum := 0 for i := 2; i <= n; i++ { if primes[i] { sum += i } } return sum } fmt.Println(sieveSum(50))
Attempts:
2 left
💡 Hint
Sum primes: 2+3+5+7+11+13+17+19+23+29+31+37+41+43+47
✗ Incorrect
The sum of primes up to 50 is 328.
