I decided to try out Sieve of Eratosthenes to find the list of primes less or equal to N. Here is my solution:
def findPrimeN(num):
result = []
multiples = []
for i in range(2, num+1):
if i not in multiples:
result.append(i)
for j in range(i*i, num+1, i):
multiples.append(j)
return result
It is not immediately clear what my run time is, I would guess O(n^2)
, but is the inner loop really using O(n)
? Moreover, that if i not in multiples:
might also be O(n), but I am not familiar with python implementation of not in list
.
Second part of my question is how to optimize it? I saw some solutions using set or collector, but do they really provide better run time like O(1)
due to look up table?
Thanks!