试图在 Python 中获取数组中的所有质数

Trying to get all prime numbers in an array in Python

我正在尝试打印出名为 'checkMe' 的数组中的所有素数。但我就是无法让它工作。我已经成功地制作了一个程序来检查它是否有一个数字,但它不适用于数组。如果有人知道问题出在哪里,请告诉我。顺便说一句:我是 python 的大菜鸟,所以它可能不是最漂亮的代码。

checkMe = range(1, 100)

dividers = []
primes = []

for y in checkMe:
    x = y
    for x in range(2, x):
        if (y/x).is_integer():
            dividers.append(x)
    if len(dividers) < 2:
        primes.append(y)

print("\n"+str(checkMe)+" has "+str(len(primes))+" primes")
print(primes)

输出:

range(1, 100) has 5 primes
[1, 2, 3, 4, 5]

预期输出:

range(1, 100) has 25 primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97]

我不想打破你的泡沫,但如果你进行一些快速谷歌搜索,你可能会找到答案。

总之你的问题的解决方法如下:

checkMe = range(1, 100)

dividers = []
primes = []

for num in range(2,100):
    prime = True
    for i in range(2,num):
        if (num%i==0):
            prime = False
            dividers.append(num)
    if prime:
        primes.append(num)

print("\n"+ str(checkMe)+ "has "+str(len(primes))+" primes")
print(primes)

逻辑正确,但您没有重置分隔线阵列。 另外你应该忽略数字 1 并且分隔符的数量应该小于 1.

这应该有效

checkMe = range(1, 100)
primes = []
for y in checkMe[1:]:
    x = y
    dividers = []
    for x in range(2, x):
        if (y/x).is_integer():
            dividers.append(x)
    if len(dividers) < 1:
        primes.append(y)
print("\n"+str(checkMe)+" has "+str(len(primes))+" primes")
print(primes)

希望对你有帮助,再见

请阅读 python 文档 里面有很多内容 https://docs.python.org/3/tutorial/controlflow.html

check_me = range(2, 100)

primes = []
for i in check_me:
    for j in range(2, i):
        if not i % j:
            break
    else:
        primes.append(i)

print(f'{check_me} as {len(primes)} primes\n', *primes)
# range(2, 100) as 25 primes
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97