简体   繁体   中英

What is the problem with this Prime checker code?

n=int(input("Enter required number: "))
for a in range(2,n):
    if n%a==0:
        print("Your number is not prime")
        break
    else:
        print("Your number is prime")
        break

It displays composite numbers as primes too.

your code just checks if your number n is divisible with 2, otherwise will consider that n is prime, with small changes your code will work:

n=int(input("Enter required number: "))

prime = True
for a in range(2, n // 2):
    if n%a==0:
        print("Your number is not prime")
        prime = False
        break

if prime:
    print("Your number is prime")

For what you're trying to do:

from math import sqrt

n=int(input("Enter required number: "))

for j in range(2, int(sqrt(n))+1):
    if n % j == 0:
        print("Not prime")
        exit()
print("Number is prime")

Would be better, why I am using sqrt

Enter required number: 10
Not prime

Enter required number: 20
Not prime

Enter required number: 17
Number is prime

You can use any here.

if any( n%i==0 for i in range(2,int(n**0.5)+1) ):
    print("Not a prime number")
else:
    print("prime number")

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