2022-11-19 17:56:26 +00:00
|
|
|
# Algorithm from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
|
|
|
|
def primesUpTo(n):
|
|
|
|
assert n >= 2, "n must be >= 2"
|
2023-05-16 20:00:37 +00:00
|
|
|
A = [True for i in range(n + 1)]
|
2022-11-19 17:56:26 +00:00
|
|
|
|
2023-05-16 20:00:37 +00:00
|
|
|
for i in range(2, n + 1):
|
2022-11-19 17:56:26 +00:00
|
|
|
if A[i]:
|
2023-05-16 20:00:37 +00:00
|
|
|
for j in range(i ** 2, n + 1, i):
|
2022-11-19 17:56:26 +00:00
|
|
|
A[j] = False
|
|
|
|
|
2023-05-16 20:00:37 +00:00
|
|
|
return set([i for i in range(2, n + 1) if A[i]])
|
2022-11-19 17:56:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
# Testing:
|
|
|
|
s = primesUpTo(1000)
|
|
|
|
print(s)
|
|
|
|
|
|
|
|
# Do some checks:
|
2023-05-16 20:00:37 +00:00
|
|
|
assert primesUpTo(30) == {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
|
2022-11-19 17:56:26 +00:00
|
|
|
assert len(primesUpTo(1000)) == 168
|
|
|
|
assert len(primesUpTo(7918)) == 999
|
|
|
|
assert len(primesUpTo(7919)) == 1000
|
|
|
|
print("All tests passed!")
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|