Skip to content

Instantly share code, notes, and snippets.

@filwaline
Last active September 20, 2022 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filwaline/64b3f59feb819e6b337d685d55433483 to your computer and use it in GitHub Desktop.
Save filwaline/64b3f59feb819e6b337d685d55433483 to your computer and use it in GitHub Desktop.
primes_generator.py
def numbers(start=0):
num = start
while True:
yield num
num += 1
def primes(seq):
num = next(seq)
_square = num ** 2
yield num
yield from primes(filter(lambda i: _square > i or i % num, seq))
if __name__ == "__main__":
# 正整数序列,从 2 开始
positive_number = numbers(start=2)
# all_primes 真的表示了所有的质数,你信不信,滑稽
all_primes = primes(positive_number)
N = 10
for i, p in enumerate(all_primes, start=1):
print(f"The {i}th prime is {p}")
if i >= N:
break
# The 1th prime is 2
# The 2th prime is 3
# The 3th prime is 5
# The 4th prime is 7
# The 5th prime is 11
# The 6th prime is 13
# The 7th prime is 17
# The 8th prime is 19
# The 9th prime is 23
# The 10th prime is 29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment