简体   繁体   中英

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.
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. 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:

  • check if it is even (mod 2)
  • check if it id divisible by itself

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.

You can verify this by adding a statement print(i) in your code. And look at the range function, this might help you out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM