Write a class called Primes This class should contain a cons

Write a class called Primes. This class should contain a constructor and a method called next_prime. The next_prime method returns the next prime number. For example:

If the user types 5 in response to the prompt, then the output should be [2, 3, 5, 7, 11].

python 2.7.13

Solution

PROGRAM CODE:

#Python program to print primes
import math

class primes:
   #constructor for the class
   def __init__(self):
       self.prime = 2
      
   #method to return the prime number
   def next_prime(self):
       nprime = 0
       while True:
           isPrime = True;
           for i in range(2, int(math.sqrt(self.prime) + 1)):
               if self.prime % i == 0:
                   isPrime = False;
                   break
           nprime = self.prime
           self.prime += 1
           if isPrime:
               return nprime
      
#testing code
n = int(input(\'How many prime numbers?\ \'))
p = primes()
prime_numbers = [ ]
for i in range(n):
   prime_num = p.next_prime();
   prime_numbers.append(prime_num);

print(prime_numbers)

OUTPUT:

Write a class called Primes. This class should contain a constructor and a method called next_prime. The next_prime method returns the next prime number. For ex

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site