gpt4 book ai didi

python代码试图找到质数。代码计算的不是质数。找不到原因

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:57 25 4
gpt4 key购买 nike

我试图在用户选择的范围内找到每个质数,列出它们并计算它们。我的代码计数和列表编号不是素数。我真的找不到为什么?有人可以帮帮我吗。

print("This code will count how many prime number exist in a certain range")
count = 0
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
prime = []
for num in range(lower, upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
break
print(prime)
print("There are", len(prime), "prime number between", lower, "and", upper)

最佳答案

问题就在这里,

    for i in range(2,num):
if (num % i) == 0: #If num is divisible by SOME i, it is not prime. Correct.
break
else: #If num is not divisible by SOME i, it is not prime. WRONG.
prime.append(num)
break

您应该像这样检查条件:如果 num 不能被任何 i 整除,则它是素数

将 else 与 for 结合使用进行最少的更改,

    for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)

阅读更多:Why does python use 'else' after for and while loops?

关于python代码试图找到质数。代码计算的不是质数。找不到原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34670035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com