0
0
DSA Pythonprogramming~20 mins

Sieve of Eratosthenes Find All Primes in DSA Python - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sieve Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Sieve for n=10
What is the output list of primes generated by the Sieve of Eratosthenes for n=10?
DSA Python
def sieve(n):
    primes = [True] * (n+1)
    primes[0] = primes[1] = False
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p * p, n+1, p):
                primes[i] = False
        p += 1
    return [x for x in range(n+1) if primes[x]]

print(sieve(10))
A[1, 2, 3, 5, 7]
B[2, 3, 4, 5, 7]
C[2, 3, 5, 7]
D[2, 3, 5, 7, 9]
Attempts:
2 left
💡 Hint
Remember primes are numbers greater than 1 with no divisors other than 1 and themselves.
Predict Output
intermediate
2:00remaining
Number of primes up to 20
How many prime numbers are there up to 20 using the Sieve of Eratosthenes?
DSA Python
def sieve_count(n):
    primes = [True] * (n+1)
    primes[0] = primes[1] = False
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p * p, n+1, p):
                primes[i] = False
        p += 1
    return sum(primes)

print(sieve_count(20))
A7
B8
C9
D6
Attempts:
2 left
💡 Hint
Count primes: 2,3,5,7,11,13,17,19
🔧 Debug
advanced
2:00remaining
Identify the error in this sieve implementation
What error will this code produce when run with n=10?
DSA Python
def sieve_bug(n):
    primes = [True] * n
    primes[0] = primes[1] = False
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p * p, n+1, p):
                primes[i] = False
        p += 1
    return [x for x in range(n) if primes[x]]

print(sieve_bug(10))
AIndexError
B[2, 3, 5, 7]
CTypeError
D[2, 3, 5, 7, 9]
Attempts:
2 left
💡 Hint
Check the list size and the indices accessed in the loop.
Predict Output
advanced
2:00remaining
Output of primes for n=1
What is the output of the sieve function when n=1?
DSA Python
def sieve(n):
    primes = [True] * (n+1)
    primes[0] = primes[1] = False
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p * p, n+1, p):
                primes[i] = False
        p += 1
    return [x for x in range(n+1) if primes[x]]

print(sieve(1))
A[1]
B[2]
C[0, 1]
D[]
Attempts:
2 left
💡 Hint
Primes start from 2, so no primes exist for n=1.
🧠 Conceptual
expert
2:00remaining
Why does the sieve 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?
ABecause all smaller multiples of p were already marked by smaller primes
BBecause p*p is the smallest prime number
CBecause 2*p is not a multiple of p
DBecause starting from 2*p would miss some prime numbers
Attempts:
2 left
💡 Hint
Think about when smaller multiples get marked.