Skip to content

improved prime number generator to check only up to sqrt(n) instead of n #1984

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 14, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion maths/prime_numbers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import Generator
import math


def primes(max: int) -> Generator[int, None, None]:
def slow_primes(max: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(primes(0))
Expand All @@ -28,6 +29,35 @@ def primes(max: int) -> Generator[int, None, None]:
yield i


def primes(max: int) -> Generator[int, None, None]:
"""
Return a list of all primes numbers up to max.
>>> list(primes(0))
[]
>>> list(primes(-1))
[]
>>> list(primes(-10))
[]
>>> list(primes(25))
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> list(primes(11))
[2, 3, 5, 7, 11]
>>> list(primes(33))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> list(primes(10000))[-1]
9973
"""
numbers: Generator = (i for i in range(1, (max + 1)))
for i in (n for n in numbers if n > 1):
# only need to check for factors up to sqrt(i)
bound = int(math.sqrt(i)) + 1
for j in range(2, bound):
if (i % j) == 0:
break
else:
yield i


if __name__ == "__main__":
number = int(input("Calculate primes up to:\n>> ").strip())
for ret in primes(number):
Expand Down