Creating Data 8 Assignments
Writing Your Own Assignments
# BEGIN QUESTION
name: q1
points: 2
Question 1. Write a function called sieve that takes in a positive integer n and returns a set of the prime numbers less than or equal to n. Use the Sieve of Eratosthenes to find the primes.# BEGIN SOLUTION
def sieve(n):
"""
Generate a set of prime numbers less than or equal to a positive integer.
"""
# BEGIN SOLUTION
is_prime = [True for _ in range(n + 1)]
p = 2
while p ** 2 <= n:
if is_prime[p]:
for i in range(p ** 2, n + 1, p):
is_prime[i] = False
p += 1
is_prime[0]= False
is_prime[1]= False
return set(i for i in range(n + 1) if is_prime[i])
# END SOLUTION
# END SOLUTIONBest Practices for Autograder Tests
Last updated