Tuesday 26 April 2011

Script to find if a number is prime or not

Below script will find if the number entered is prime or not

while True:
    try:
        input = int(input("Enter a number: "))
        break
    except Exception, e:
        print e

a = []
if input == 0:
    print input, "is  not a valid number"
elif input == 1:
    print input, "is not a prime number"
else:
    for i in range(input):
        if i == 0:
            pass
        else:
            a.append(input % i)
    if a.count(0) > 1:
        print input, "is not a prime number"
    else:
        print input, "is a prime number"

Output:
[madhu@localhost tmp]$ python prime.py
Enter a number: 2
2 is a prime number
[madhu@localhost tmp]$ python prime.py
Enter a number: 10
10 is not a prime number

No comments:

Post a Comment