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

  • 3
    Think about this for a second. It's going to check 2, and then it will print one message or the other and then `break`. Will it ever check 3? No. You've created an even/odd checker, not a prime checker. – hobbs Jan 05 '20 at 16:17

3 Answers3

1

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")
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

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
BpY
  • 403
  • 5
  • 12
  • but if `n` is prime your code won't produce any output. Since OP is a beginner consider adding how to print if a number is `prime`.Cheers. Happy New Year. – Ch3steR Jan 05 '20 at 17:07
  • @ch3ster I took what you said on board and edited my code, Happy new year – BpY Jan 05 '20 at 17:25
  • Don't use `exit` here since it will kill the whole process and checking if a number is prime or not maybe a small module of a big program. Check my answer might help you. – Ch3steR Jan 05 '20 at 17:30
  • As you said OP is a beginner, I would guess this is the entire program and is probably for a school project so this implementation is perfectly valid in this case. – BpY Jan 05 '20 at 17:47
  • There's inconsistency in your program your killing the process only if the number is not prime. adding another exit() after print(number is prime) will be enough. – Ch3steR Jan 06 '20 at 03:49
  • No it isn't take out the exit and you'll see what happens `Not prime` is printed multiple times, then `Prime` is also printed – BpY Jan 06 '20 at 11:03
  • I meant to say add another exit() after `print('number is prime')`. So that the process will be killed if it's either prime or not prime. – Ch3steR Jan 06 '20 at 11:07
  • `exit()` is not needed at the end as the program ends after this line anyway, it would be overkill and actually computationally inefficient – BpY Jan 06 '20 at 14:08
0

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")
Ch3steR
  • 20,090
  • 4
  • 28
  • 58