Fly by Night
Fly by Night

Reputation: 133

Sieve of Eratosthenes with nested for loops

This is a very simple question about python. I was trying to get a list of prime numbers so I tried

primes = [2]

for i in primes:
   for j in range(50):
      if j%i != 0:
         primes.append(j)

print(primes)

But it just goes into an indefinite loop.

Upvotes: 0

Views: 138

Answers (1)

XxJames07-
XxJames07-

Reputation: 1826

You are looping over a list and appending to it that will make that infinite process as the iteration just takes the index but you can put an end by defining the limit value

There are lots of methods to achieve that, but i would suggest to just break if the number is bigger than the limit:

primes = [2]
limit = 40
for i in primes:
   if primes[-1]>limit:break
   for j in range(50):
      if j%i != 0:
         primes.append(j)

print(primes)

Before that, you should know what you are doing, an advice is to first do your calculations on paper and then code them.

Your code provides different results as they are not prime, first come up with an algorithm or search online.

using the provided algorithm you should be able to use the pseudocode to come up with one on your own, here is an example:

from math import isqrt
limit = 40
primes = [True]*limit
primes[0] = False
primes[1] = False
for i in range(2,isqrt(limit-1)+1):
    if primes[i]:
        for j in range(i*i,limit,i):
            primes[j] = False
from numpy import where
print(list(where(primes)[0]))
# >>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]

Upvotes: 1

Related Questions