[英]What's the problem in this code for finding whether a number is prime?
Whenever I executed the code I get wrong answers only.每当我执行代码时,我只会得到错误的答案。 I try for 2 numbers 55 and 89 and I get same answer for both no matter how I alter the code.
我尝试了 2 个数字 55 和 89,无论我如何更改代码,我都会得到相同的答案。
I know it's a dumb question but I tried a lot of ways but it doesn't work.我知道这是一个愚蠢的问题,但我尝试了很多方法,但它不起作用。 I guess it's some kind of indentation problem.
我想这是某种缩进问题。 For me it's a bit hard to get into python because of no use of brackets so please help this noob.
对我来说,进入 python 有点困难,因为没有使用括号,所以请帮助这个菜鸟。 Thank you
谢谢
a=int(input("Enter the number you want to check for prime: \n"))
b = False
for i in (2,a):
if(a%i)==0:
b = True
break
i=i+1
if b:
print("The number is not a prime number")
else:
print("The number is a prime number")
Ok, so your error is not a code error.好的,所以您的错误不是代码错误。 Your algorithm is incorrect.
你的算法不正确。 For any given number you do 2 checks:
对于任何给定的数字,您需要进行 2 次检查:
This does not say anything about it being a prime number.这并没有说明它是质数。 This is probably a homework assignment so I will not give you a working solution here, but I think that this should help you on your way.
这可能是一个家庭作业,所以我不会在这里给你一个可行的解决方案,但我认为这应该对你有所帮助。
Ok maybe I see something else: your loop for i in (2,a)
and later on i=i+1
does not do what you think it does.好吧,也许我看到了其他东西:您
for i in (2,a)
循环以及稍后的i=i+1
并没有按照您的想法执行。
You can verify this by adding a statement print(i)
in your code.您可以通过在代码中添加语句
print(i)
来验证这一点。 And look at the range function, this might help you out.并查看 function范围,这可能会对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.