| 1 | import math |
| 2 | |
| 3 | def sieve(n): |
| 4 | in_prime = [] |
| 5 | start = 2 |
| 6 | end = int(math.sqrt(n)) # Size of every segment |
| 7 | temp = [True] * (end + 1) |
| 8 | prime = [] |
| 9 | |
| 10 | while(start <= end): |
| 11 | if temp[start] == True: |
| 12 | in_prime.append(start) |
| 13 | for i in range(start*start, end+1, start): |
| 14 | if temp[i] == True: |
| 15 | temp[i] = False |
| 16 | start += 1 |
| 17 | prime += in_prime |
| 18 | |
| 19 | low = end + 1 |
| 20 | high = low + end - 1 |
| 21 | if high > n: |
| 22 | high = n |
| 23 | |
| 24 | while(low <= n): |
| 25 | temp = [True] * (high-low+1) |
| 26 | for each in in_prime: |
| 27 | |
| 28 | t = math.floor(low / each) * each |
| 29 | if t < low: |
| 30 | t += each |
| 31 | |
| 32 | for j in range(t, high+1, each): |
| 33 | temp[j - low] = False |
| 34 | |
| 35 | for j in range(len(temp)): |
| 36 | if temp[j] == True: |
| 37 | prime.append(j+low) |
| 38 | |
| 39 | low = high + 1 |
| 40 | high = low + end - 1 |
| 41 | if high > n: |
| 42 | high = n |
| 43 | |
| 44 | return prime |
| 45 | |
| 46 | print(sieve(10**6)) |