vendredi 29 décembre 2017

this program executes both if and else

import math
while True:
 n=(raw_input("Please enter a number to check if it is prime or not " ))
 if n == "gate":
    exit()
 n=int(n)
 x=int( math.sqrt(n))
 if n%2==0:
    print n , "is an even number"
 else:
    for i in range(3,x+1,2):
        if n%i==0 :
           print " Composite",n, "div by" ,i ,"."
        else:
           print "PRIME"

This code runs fine if I enter an even but acts abnormal when I input an odd or prime integer. It identifies composite accurately. Irrespective of prime or composite odd it prints PRIME many times.(sometimes twice or thrice). The output is like:

Please enter a number to check if it is prime or not  53
PRIME
PRIME
PRIME
Please enter a number to check if it is prime or not  36
36 is an even number
Please enter a number to check if it is prime or not  21
Composite 21 div by 3 .
Please enter a number to check if it is prime or not  23
PRIME
Please enter a number to check if it is prime or not  37
PRIME
PRIME
Please enter a number to check if it is prime or not  

I think I have done some indentation error or implemented while loop incorrectly. please help.

Aucun commentaire:

Enregistrer un commentaire