How to check whether a number is prime or not using Python?

PythonServer Side ProgrammingProgramming

Principle used in following solution to this problem is to divide given number with all from 3 its square root, a number's square root is largest possible factor beyond which it is not necessary to check if it is divisible by any other number to decide that it is prime number.

The function returns false for all numbers divisible by 2 and less than 2. For others return value of all) function will be false if it is divisible by any number upto its square root and true if it is not divisible by any number

Example

def is_prime(a):
    if a < 2:
        return False
    elif a!=2 and a % 2 == 0:
        return False
    else:
        return all (a % i for i in range(3, int(a**0.5)+1) )
num=int(input('enter a number'))
if is_prime(num)==True:
    print ("{} is a prime number".format(num))
else:
    print ("{} is not a prime number".format(num))

Output

Sample run of above program −

enter a number24
24 is not a prime number
enter a number47
47 is a prime number
raja
Published on 06-Mar-2018 00:48:10
Advertisements