[英]How do I get a defined function in python to loop whilst using the return function?
I have written a python code to generate a list of all Mersenne primes q for p less than n_max.
我编写了一个 python 代码来生成一个所有梅森素数 q 的列表,其中 p 小于 n_max。 This function works when using
return
but this stops the loop and only outputs the first mersenne prime 3.这个函数在使用
return
但这会停止循环并且只输出第一个梅森素数 3。
def primes(n):
i, p, ps, m = 0, 3, [2], n // 2
sieve = [True] * m
while p <= n:
if sieve[i]:
ps.append(p)
for j in range((p*p-3)//2, m, p):
sieve[j] = False
i, p = i+1, p+2
return ps
def lucas_lehmer(p):
if p == 2: return True
m, i, s = pow(2,p) - 1, 3, 4
while i <= p:
i, s = i+1, (pow(s,2) - 2) % m
return s == 0
def mersenne_prime(n_max):
L1 = []
for p in primes(n_max):
if lucas_lehmer(p):
q=(2**p)-1
L1.append(q)
return L1
Can anyone give a solution so that the code returns all the mersenne primes for which p in q=2**p-1
is less than n_max?谁能给出一个解决方案,以便代码返回
q=2**p-1
小于 n_max 的所有梅森素数?
You need to intialize a list a for storing all the primes.您需要初始化一个列表 a 来存储所有素数。 Then append q to it.
然后将 q 附加到它。
def mersenne_prime(n_max):
a=[]
for p in primes(n_max):
print(p)
if lucas_lehmer2(p):
q=(2**p)-1
a.append(a)
return a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.