Python Function to check Prime Number


In this example, we will learn whether the entered number is a prime number or not using a user-defined function.
A prime number is a number that is divisible by 1 and itself. The same principle we are going to explore in this example.

Python Function to check the primary number [ Old method ]

def check_prime(n):
    flag = True
    for x in range(2, n//2):
        if n % x == 0:
            flag = False

    return flag

if __name__ == "__main__":
    n = int(input('Enter any integer number  : '))
    result = check_prime(n)
    print("Prime Number " if (result) else '"Not prime Number')

Output of the above python program

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\functions\check_prime.py"
Enter any integer number  : 16
"Not prime Number

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\functions\check_prime.py"
Enter any integer number  : 17
Prime Number

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\functions\check_prime.py"
Enter any integer number  : 1
Prime Number

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\functions\check_prime.py"
Enter any integer number  : 2
Prime Number

A second and Most efficient method to check prime Number

from math import sqrt
def prime_number(n):
    flag = True
    for x in range(2, int(sqrt(n))+1):
        if n % x == 0:
            flag = False
    return flag

Implementation of the above function to check Prime number. The above function tried to divide all the number between 2 and sqrt( ) of the number and this is the shortest method to check prime number.

if __name__ == "__main__":
    if(prime_number(12)):
        print('Prime Number')
    else:
        print('Not a prime Number')

The same function can be used to find out the prime number between two numbers.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.