2

This is my code:

import math

n=100

prime=[]
[prime.append(i) for i in range(2,n)]
i=2

"""for i in range(2,int(math.sqrt(n))):"""
while i*i <= n:
    for j in range(2,n+1):
        if i * j in prime:
            prime.remove(i*j)
    i +=1

print(prime)

Now this works, but when I changed n from 100 to 10000 it blows. How can I fasten it or should I use generator way? Thank you.

3 Answers3

2

The reason that the time explodes is that the data structures you have used make this a O(n^2) algorithm.

Using a set will allow for equivalent logic while reducing it to a O(n) algorithm:

import math

n=100

prime = set(i for i in range(2,n))
i=2

while i*i <= n:
    for j in range(2,n+1):
        if i * j in prime:
            prime.remove(i*j)
    i +=1

print(prime)

The operation that is particularly expensive is i * j in prime. If prime is a list, it potentially has to scan through the entire list. For a set, it doesn't have to scan through all the elements.

lehiester
  • 726
  • 1
  • 5
  • 16
0

I have used:

def gen_primes():
    D = {}

    q = 2

    while True:
        if q not in D:
            yield q
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]

        q += 1

Got it from an old post here on SO... Will look for it and credit it when I find it,

augustoccesar
  • 598
  • 7
  • 29
Anand
  • 1,461
  • 1
  • 10
  • 21
  • 1
    Found it: https://stackoverflow.com/questions/567222/simple-prime-generator-in-python – Anand Jan 29 '18 at 13:41
0

We can do this with only one loop :

num = 407
if num > 1:
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
else:
   print(num,"is not a prime number")
Léo R.
  • 3,041
  • 1
  • 8
  • 21