用Python寻找前n个质数output是这样:Find the first M prime numbers100 :3 is a prime number1 :5 is a prime number2 :7 is a prime number3 :11 is a prime number4 :13 is a prime number5 :17 is a prime number6 :19 is a prime number7 :23 is a pri
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/25 20:17:31
用Python寻找前n个质数output是这样:Find the first M prime numbers100 :3 is a prime number1 :5 is a prime number2 :7 is a prime number3 :11 is a prime number4 :13 is a prime number5 :17 is a prime number6 :19 is a prime number7 :23 is a pri
用Python寻找前n个质数
output是这样:
Find the first M prime numbers
10
0 :3 is a prime number
1 :5 is a prime number
2 :7 is a prime number
3 :11 is a prime number
4 :13 is a prime number
5 :17 is a prime number
6 :19 is a prime number
7 :23 is a prime number
8 :29 is a prime number
9 :31 is a prime number
用Python寻找前n个质数output是这样:Find the first M prime numbers100 :3 is a prime number1 :5 is a prime number2 :7 is a prime number3 :11 is a prime number4 :13 is a prime number5 :17 is a prime number6 :19 is a prime number7 :23 is a pri
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开始用注释的两行替换这两行下面的行