Python program to print infinite prime numbers

Viewed 30

I want to print infinite Prime numbers. How can I do it? I don't want the program to end of its own. How do I do it?

The code I tried is:

i = 2
while True:
  while i>1:
    for j in range(2, i):
      if (i%j)==0:
        break
      else:
        print(i)

But, the above code does not work.

3 Answers

Schematically, proceed like this:

def is_prime(n):
    """Returns True if n is a prime number."""
    """implementation left as an exercise"""

n = 1

while True:
    if is_prime(n):
        print(n)
    n += 1

Once you get this code working, there are many ways to improve it.

I suggest you search Internet or stackoverflow for an answer why your code is not working. Use python print prime numbers for your search ( gives on stackoverflow 1_272 results ) and put for an upper limit of primes to print an almost infinite large number or use an endless loop like you are trying in your attempt having fun out of heating up your CPU and locking your computer up in an infinite loop.

Generally it is not possible to let a computer endless print primes because with large enough prime values you reach physical limits of the hardware what will make any program written in any programming language fail at some point with an memory overflow or with exceeding storage media capacity.

See here ( Print series of prime numbers in python ) to start your prime journey with and consider that writing programs locked up in an endless loop is generally not a good idea.

P.S. to experience infinite large prime number you have first make sure your lifespan gets infinite and consider that stackoverflow is not the right site to ask the question how to achieve an infinite life span.

You see, mathematically there is no way to generate infinite prime numbers as there is no formula to generate prime numbers. So you can't really generate infinite prime numbers.

Related