我想创建一个primelist生成器,检查一个数字是否可以被任何小于它自身的素数整除,如果不是,它会被附加到primelist。但我的程序只返回有趣的列表,如示例中的那个:
primelist=[2]
for m in range (10):
for k in primelist:
if m%k == 0 :
continue
else:
primelist.append(m)
print (primelist)
打印清单:
[2, 1, 3, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
答案 0 :(得分:1)
您需要使用标记来检查所有数字,您目前过早追加。试试这个:
primelist=[2]
for m in range (2,12):
for k in primelist:
if m%k == 0 :
break
else:
primelist.append(m)
print (primelist)
答案 1 :(得分:0)
每次在primelist中的任何数字给出余数不等于0(f.e。4%3 !=0
所以它附加)时,你都会添加每个数字。相反,只有当它为所有素数
primelist = [2]
for m in range(10):
if all([m%i != 0 for i in primelist]): #If all remainders are different than 0 is prime
primelist.append(m)
print(primelist)
这不是很好。一个更好的算法可能是
primelist = [2]
def isPrime(num):
from math import sqrt
for p in primelist:
if p > int(sqrt(num)+1): #Just test until sqrt(num)
return True
elif num%p == 0:
return False
return True
primelist = [2]
for m in range(3, numberWanted):
if isPrime(m):
primelist.append(m)
print(primelist)
这种方式isPrime
是懒惰的函数,不需要针对每个引物编号进行测试(对于大数字可能有用)
修改:完整isPrime
功能:
def isPrime(num):
from math import sqrt
for p in range(2, int(sqrt(num)+1)):
if num%p==0:
return False
return True
此函数的问题在于,对于大数字,它将针对整个范围[2 - sqrt(num)]进行测试,之前的函数仅针对先前计算的素数(primelist
)进行测试。第一个仅在您按顺序填充primelist