Just checked my own algorithm and found several mistakes. Here is the correct algorithm: def prime(n): set = [2] + range(3,n, 2) for n in range(3, int(math.sqrt(n))+1, 2): set = [x for x in set if x == n or x % n != 0] return set