6 Best Ways To Check If Number Is Prime In Python

This article will learn how to check if a number is prime or not in Python. Usually, we all know some common methods using library functions or without using library functions. But how many of us know that there are 6 ways to check a prime number. Maybe some of us will be familiar with some methods. But this article will teach you all the possible ways. Let us move on to check if a number is prime or not.

In the number system, we have two types of numbers. They are Prime and composite. Prime numbers are the numbers that are not the product of any other numbers. These numbers are always natural numbers. For example, 13 is a prime number. Because we cannot get this number as a product of any other two numbers except to the product of 1, on the other hand, if we take 4, it will show a result as a composite because it is a product of 2X2. I hope now all are clear about prime numbers.

The following methods are available:

  1. isprime() function
  2. If-else statements
  3. Math module
  4. Sympy library
  5. PrimePy library
  6. is_integer function

6 Ways To Check If a Number Is Prime in Python

1: Using isprime()

Example:

def isprime(num):
    for n in range(2,int(num**0.5)+1):
        if num%n==0:
            return False
    return True
print(isprime(7))
print(isprime(8))

This method is implemented using function. It will return True if the number is prime. Otherwise, it will return False. First checking with 7 and then with 8.

Output

True
False

Example:

def isprime(num):
    if num==2 or num==3:
        return True
    if num%2==0 or num<2:
        return False
    for n in range(3,int(num**0.5)+1,2):   
        if num%n==0:
            return False    
    return True
print(isprime(13))
print(isprime(18))

This method is implemented using function. It will return True if the number is prime. Otherwise, it will return False. First checking with 13 and then with 18.

Output

True
False

Example:

def isprime(num):
  if num == 2 or num == 3:
      return True
  if num < 2 or num%2 == 0:
      return False
  if num < 9:
      return True
  if num%3 == 0:
      return False
  a = int(num**0.5)
  b = 5
  while b <= a:
    print ('\t',b)
    if num%b == 0:
        return False
    if num%(b+2) == 0:
        return False
    b=b+6
  return True
print(isprime(15))
print(isprime(2))

This method is implemented using function. It will return True if the number is prime. Otherwise, it will return False. First checking with 15 and then with 2.

Output

False
True

Example:

def isprime(num):
    if num> 1:  
        for n in range(2,num):  
            if (num % n) == 0:  
                return False
        return True
    else:
        return False
print(isprime(64))
print(isprime(5))

This method is implemented using function. It will return True if the number is prime. Otherwise, it will return False—first checking with 64 and then with 5.

Output

False
True

2: Using if-else statements

n=int(input("Enter a number:"))
if n>1:
    for i in range(2,n//2):
        if(n%i)==0:
            print(n,"is not a prime number")
            break
    else:
        print(n,"is a prime number")
else:
    print(n,"is neither prime nor composite")

This code is normally using loops. Here we are getting a number as an input from the user. It performs the code and gives the result to the user. If the user gives 1 as an input, it will display neither prime nor composite.

Output

Enter a number:14
14 is not a prime number
Enter a number:3
3 is a prime number
Enter a number:1
1 is neither prime nor composite

3: Using math function to check if number is prime python

Math is a module that is already available in the python library. This module contains a lot of mathematical functions. To access this module, we have to import the module as:

import math

Here we are using math.sqrt to check if the number is prime or not. sqrt() is a built-in function in python.

Syntax

math.sqrt(x)

Parameter

x – that can be any value.

Returns

It returns the square root of the x value.

Code

import math
def isprime(num):
    a=2
    while a<=math.sqrt(num):
        if num%a<1:
            return False
        a=a+1
    return num>1
print(isprime(14))
print(isprime(7))

Output

False
True

4: Using sympy module

Sympy is a module in the python library. It only depends on mpmath. Here we are simply using a sympy module. The pip command line to install the module is:

pip install sympy

Syntax

sympy.isprime(x)

Parameter

x – it is an input value

Returns

Boolean values

Example:

import sympy
print(sympy.isprime(90))

Output

False

Example:

from sympy import *
print(isprime(19))

Output

True

Example:

import sympy.ntheory as nt
print(nt.isprime(8))

Output

False

5: Using primePy library to check if a number is prime or not

The primePy is a library that is useful to perform the operations regarding prime numbers. Here we are using primePy to check whether a number is prime or not. The pip command to install the primePy module:

pip install primePy

Syntax

primePy.check(n)

Parameter

n – It is an input number

Returns

Boolean values

Code

from primePy import primes
print(primes.check(63))

Output

False

6: Using is_integer function

is_integer is a built-in function that is useful to check if the given number is an integer or not. It is also useful to check if it is prime or not.

Syntax

float.is_integer()

Parameter

floating number

Returns

Boolean values (True or False)

Example:

def prime(num):
    a=[]
    for i in range (1, num+1):
        if (num/i).is_integer():
            a.append(i)
    if len(a)==2:
        print("Prime")
    else:
        print("Not Prime")
prime(2)

Output

Prime

Learn Something New: How to generate a random prime number?

import random
def range_primes(a, b):
    prime = []
    for i in range(a, b):
        is_prime = True
        for n in range(2, i):
            if i % n == 0:
                is_prime = False
        if is_prime:
            prime.append(i)
    return prime
prime= range_primes(1,100)
random_prime = random.choice(prime)
print("Random Prime Number is:", random_prime)

Output

Random Prime Number is: 11

Check if Number is Prime Using Recursion

You can check for all prime numbers using the Prime function.  Simply pass the number as th3 argument.

i=2

def Prime(no, i):
    if no == i:
        return True
    elif no % i == 0:
        return False

    return Prime(no, i + 1)

Here, we will recursively call the Prime function to check if the number is prime.

1. What is a prime number?

Prime numbers are the numbers that are not the product of any other numbers. These numbers are always natural numbers.

2. How to check if the number is prime or not using loops?

To check if a number is prime or not. We have to create a for loop to iterate the numbers. Suppose the number is greater than one. It will check whether a number is a product of any number. If it is, it displays False as a result.

Conclusion

Here we have briefly learned about how to check if a number is prime or not. We have learned many possible ways. With that, we also saw how to generate a prime number. We hope this article is helpful. Try to solve the programs on your own to gain more knowledge.

Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sid
Sid
2 years ago

Methods 1 through 3 are all the same method. They are only slight variations to be selective about which numbers to iterate. How about adding a method that uses the Sieve of Eratosthenes, and one that uses a lookup table?

Python Pool
Admin
2 years ago
Reply to  Sid

Great catch! I’ll update the post with these methods.

Gabriel
Gabriel
2 years ago

Hi,

method 1.5 cannot work and should be updated :p

Cheers

Pratik Kinage
Admin
2 years ago
Reply to  Gabriel

Hi Gabriel,

Thank you for informing me :). I’ve updated the post accordingly.

Regards,
Pratik

ITech
ITech
2 years ago

I believe your purpose in the statement:
“int(num**1/2)”

is to refer to the root of num, but because you didn’t use parenthesis it becomes:
“int(num/2)”

if you do correct it to:
“int(num**0.5)”

the range needs to be changed in some of your codes here or else the range will be null for lower numbers, I checked for example with 3 and 5.

Pratik Kinage
Admin
2 years ago
Reply to  ITech

Correct. Thank you for pointing it out!