0

I'm a beginner in python my code takes so much time just in finding the primes bellow 2 million he works fine with numbers like thousands but a million is a big number, anyone has an idea about whats can I do thank you in advance:

arr = list()
for i in range(2, 200000):
    for j in range(2, i + 1):
        if i % j == 0 and i == j:
            arr.append(i)
        elif i % j == 0 and i != j:
            break
        else:
            continue
print(arr)

2 Answers2

0

First of all, you could improve your list by using some logic. Exclude the number two and skip every even number:

for i in range(3, 200000, 2):

The same can be done in the second loop

You can also exclude all squares of the already found primes and so on

Vlad
  • 184
  • 6
0

The first step towards developing a more efficient algorithm would be to try the Sieve of Eratosthenes (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes):

limit = 200000
arr = list(range(limit))
# The algorithm starts at 2
for num in arr[2:]:
    if arr[num]:
        idx = 2 * num
        while idx < limit:
            arr[idx] = 0
            idx += num

primes = [elem for elem in arr if elem > 1]
nenb
  • 63
  • 5
  • Thanks for pointing this out. I've now edited my answer. – nenb Nov 27 '20 at 15:35
  • You can't use a slice of `arr` (which copies `arr`) without unnecessarily sieving a whole bunch of primes. You *want* the `if num:`, but you need to switch `for num in arr[2:]:` to something like `for num in itertools.islice(arr, 2, None):` so it sees a live view of your sieved `list` and the `if num:` can skip sieving when the number is already known non-prime. – ShadowRanger Nov 27 '20 at 15:39
  • @ShadowRanger Or they could've switched to `if arr[num]:`. – superb rain Nov 27 '20 at 15:40
  • @ShadowRanger That was very helpful, thanks! It's essentially what I wanted to do originally, but I didn't quite manage it. I have (again) edited my answer to reflect the suggestion from superb rain, because this is much closer to what I was trying to do originally. – nenb Nov 27 '20 at 16:05
  • @nenb thanks you that very help – Abdelilah Zaidane Nov 28 '20 at 13:30