Question: Problem 2. Prime Number Generator Part a). Iterator Class Write a class called PrimeSeq that generates the sequence of the first n prime numbers, starting

Problem 2. Prime Number Generator Part a). Iterator Class Write a class called PrimeSeq that generates the sequence of the first n prime numbers, starting with 2, 3, 5,.... The class must comply with the iterator interface and must support the for statement. The __next__() method must return the next prime number from the sequence or throw StopIteration if n primes have already been generated.

This class should work like this:

# prints in order the first 100 prime numbers: 2,3,5,... 

primeseq = PrimeSeq(100)

for p in primeseq: print(p)

yield

Extra credit part, for 5 points:

# Create a list with the first 100 prime numbers: 

primes_lst = [p for p in PrimeSeq(100)] print(primes_lst)

A PrimeSeq object must use an instance attribute list self.__primes that accumulates all prime numbers computed until the most recent call to __next__(). Use that to speed up the computation of the next prime number from the sequence by checking divisibility for a number p only with prime divisors <= sqrt(p).

Part b). Generator

Write a Python generator called prime_gen(n) that takes an integer n >= 0 and produces the sequence of the first n prime numbers. This generator is defined as a function that uses the keyword to output a value, as seen on the Chapter 16 lecture PDF file, on slides 60-70. This generator produces the same number sequence as the PrimeSeq class from part a). Here is how it can be used in a for loop to print the first 10 prime numbers:

for p in prime_gen(10): print(p)

Write the code from parts a) and b) in a file p2.py.

Add in this file a function called main() that demonstrates both the PrimeSeq class and the prime_gen() generator by creating and printing lists with the first 100 prime numbers.

in python

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!