[英]How to print a True/False list for Prime numbers with Indexes in Python?
我的 function 为素数输出 True,为非素数输出 False。
def is_prime(x):
if x < 2:
return False
else:
for n in range(2,x-1):
if x % n == 0:
return False
return True
我想 output 对应的 True/False 语句的索引号,如下所示:
[0][False]
[1][False]
[2][True]
[3][True]
[4][False]
[5][True]
完成此任务的最简单方法是什么?
def is_prime(x):
if x < 2:
return False
else:
for n in range(2,x-1):
if x % n == 0:
return False
return True
def num_range(x):
for i in range(x):
print([i],[is_prime(i)])
num_range(5) # send how many numbers you want to print
这给出了 output
[0] [False]
[1] [False]
[2] [True]
[3] [True]
[4] [False]
因为,您实际上是在归还埃拉托色尼筛子中的标志。 也许您应该直接使用该方法:
def sieve(x):
result = [False]*2+[True]*(x-1)
p,i = 2,1 # 2,3,5,7,...
while p*p<=x: # only up to √x
if result[p]: # found a prime
result[p*p::p] = [False]*len(result[p*p::p]) # flag multiples
p,i = p+i,2 # next candidate
return result
output:
x = 10
for i,isPrime in enumerate(sieve(x)):
print([i],[isPrime])
[0] [False]
[1] [False]
[2] [True]
[3] [True]
[4] [False]
[5] [True]
[6] [False]
[7] [True]
[8] [False]
[9] [False]
[10] [False]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.