Home > Back-end >  Endless error while creating a list containing first 100 prime numbers
Endless error while creating a list containing first 100 prime numbers

Time:10-09

So the purpose is: Using a while loop and your is_prime function, define a list containing the first 100 prime numbers.

I have my is_prime function code like this:

def is_prime(n):
    if isinstance(n,int) == False:
        return False
    if n%2==0 or n<2: 
        return False
    if n==2 or n==3: 
        return True
    if n%3 == 0: 
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

It works and then I wrote:

first_primes = []
while len(first_primes)<100:
    for j in range(0,10**6):
        if is_prime(j) == True:
            first_primes.append(j)
first_primes

However, the code runs endlessly, when I stop it I get

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-20-0abfdab33706> in <module>
      2 while len(first_primes)<100:
      3     for j in range(0,10**6):
----> 4         if is_prime(j) == True:
      5             first_primes.append(j)

<ipython-input-18-a97bbcf0d07f> in is_prime(n)
      9         return False
     10     for i in range(2, n):
---> 11         if n % i == 0:
     12             return False
     13     return True"

Why this error happens? How can I fix it? Thank you for any help!

CodePudding user response:

It's not an endless loop, just a very long and slow one. Your for loop completes no matter what, so you are waiting until you find every prime that is smaller than 10^6. Your while condition will only be processed after the for loop is finished. Change your code to:

first_primes = []
for j in range(0, 10**6):
    if is_prime(j):
        first_primes.append(j)
    if len(first_primes) >= 100:
        break

If this is an assignment and you must use a while loop, then try:

first_primes = []
j = 2
while len(first_primes) < 100:
    if is_prime(j):
        first_primes.append(j)
    j  = 1

Also note that your is_prime function (incorrectly) returns False for 2 as @ddejohn mentioned.

  • Related