用Python寻找前n个质数
发布网友
发布时间:2022-09-26 21:32
我来回答
共1个回答
热心网友
时间:2023-10-03 16:25
from itertools import count
from math import sqrt
def format_primes(fn):
def add_descriptoin(n):
primes = fn(n)
for i, p in enumerate(primes):
print("{} : {} is a prime number".format(i, p))
return add_descriptoin
@format_primes
def first_primes(n):
def prime_gen():
primes = []
for n in count(2):
if all(n%p for p in primes if p <= sqrt(n)):
primes.append(n)
yield n
primes = []
for i, j in enumerate(prime_gen()):
# if i < n:
if i < (n+1):
primes.append(j)
else:
break
# return primes
return primes[1:]
print("Find the first M prime numbers")
# python 2.x输入数据的话,要作相应修改
M = input("M? ")
first_primes(M)
按你的示例从3开始打印的,如果要从2开始用注释的两行替换这两行下面的行
热心网友
时间:2023-10-03 16:27
from itertools import count
from math import sqrt
def format_primes(fn):
def add_descriptoin(n):
primes = fn(n)
for i, p in enumerate(primes):
print("{} : {} is a prime number".format(i, p))
return add_descriptoin
@format_primes
def first_primes(n):
def prime_gen():
primes = []
for n in count(2):
if all(n%p for p in primes if p <= sqrt(n)):
primes.append(n)
yield n
primes = []
for i, j in enumerate(prime_gen()):
# if i < n:
if i < (n+1):
primes.append(j)
else:
break
# return primes
return primes[1:]
print("Find the first M prime numbers")
# python 2.x输入数据的话,要作相应修改
M = input("M? ")
first_primes(M)
按你的示例从3开始打印的,如果要从2开始用注释的两行替换这两行下面的行