mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-05 09:21:13 +08:00
improved prime numbers implementation (#1606)
* improved prime numbers implementation * fixup! Format Python code with psf/black push * fix type hint * fixup! Format Python code with psf/black push * fix doctests * updating DIRECTORY.md * added prime tests with negative numbers * using for instead filter * updating DIRECTORY.md * Remove unused typing.List * Remove tab indentation * print("Sorted order is:", " ".join(a))
This commit is contained in:

committed by
Christian Clauss

parent
ccc1ff2ce8
commit
938dd0bbb5
@ -1,28 +1,34 @@
|
||||
from typing import List
|
||||
from typing import Generator
|
||||
|
||||
|
||||
def primes(max: int) -> List[int]:
|
||||
def primes(max: int) -> Generator[int, None, None]:
|
||||
"""
|
||||
Return a list of all primes numbers up to max.
|
||||
>>> primes(10)
|
||||
[2, 3, 5, 7]
|
||||
>>> primes(11)
|
||||
[2, 3, 5, 7, 11]
|
||||
>>> primes(25)
|
||||
>>> list(primes(0))
|
||||
[]
|
||||
>>> list(primes(-1))
|
||||
[]
|
||||
>>> list(primes(-10))
|
||||
[]
|
||||
>>> list(primes(25))
|
||||
[2, 3, 5, 7, 11, 13, 17, 19, 23]
|
||||
>>> primes(1_000_000)[-1]
|
||||
999983
|
||||
>>> 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
|
||||
"""
|
||||
max += 1
|
||||
numbers = [False] * max
|
||||
ret = []
|
||||
for i in range(2, max):
|
||||
if not numbers[i]:
|
||||
for j in range(i, max, i):
|
||||
numbers[j] = True
|
||||
ret.append(i)
|
||||
return ret
|
||||
numbers: Generator = (i for i in range(1, (max + 1)))
|
||||
for i in (n for n in numbers if n > 1):
|
||||
for j in range(2, i):
|
||||
if (i % j) == 0:
|
||||
break
|
||||
else:
|
||||
yield i
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(primes(int(input("Calculate primes up to:\n>> "))))
|
||||
number = int(input("Calculate primes up to:\n>> ").strip())
|
||||
for ret in primes(number):
|
||||
print(ret)
|
||||
|
Reference in New Issue
Block a user