Is prime number function python?

Example to check whether an integer is a prime number or not using for loop and if...else statement. If the number is not prime, it's explained in output why it is not a prime number.

To understand this example, you should have the knowledge of the following Python programming topics:

  • Python if...else Statement
  • Python for Loop
  • Python break and continue

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6.


Example 1: Using a flag variable

# Program to check if a number is prime or not

num = 29

# To take input from the user
#num = int(input("Enter a number: "))

# define a flag variable
flag = False

# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break

# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")

In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop.

Outside the loop, we check if flag is True or False.

  • If it is True, num is not a prime number.
  • If it is False, num is a prime number.

Note: We can improve our program by decreasing the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1.

We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)). The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. Otherwise, the number is prime.

You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.

In Python, we can also use the for...else statement to do this task without using an additional flag variable.


Example 2: Using a for...else statement

# Program to check if a number is prime or not

num = 407

# To take input from the user
#num = int(input("Enter a number: "))

# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
       
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")

Output

407 is not a prime number
11 times 37 is 407

Here, we have used a for..else statement to check if num is prime.

It works on the logic that the else clause of the for loop runs if and only if we don't break out the for loop. That condition is met only when no factors are found, which means that the given number is prime.

So, in the else clause, we print that the number is prime.

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. functions
  2. if-else statements
  3. math module
  4. sympy library
  5. primePy library
  6. is_integer function

  • Method 1: Using isprime() to check if a number is prime or not in python
    • 1.1 Code
    • 1.2 Code
    • 1.3 Code
    • 1.4 Code
  • Method 2: Using if-else statements to check if a number is prime or not
  • Method 3: Using math function to check if a number is prime or not
    • Syntax
    • Parameter
    • Returns
    • Code
  • Method 4: Using sympy module to check if a number is prime or not
    • Syntax
    • Parameter
    • Returns
    • 4.1 Code
    • 4.2 Code
    • 4.3 Code
  • Method 5: Using primePy library to check if a number is prime or not
    • Syntax
    • Parameter
    • Returns
    • Code
  • Method 6: Using is_integer function to check if a number is prime or not
    • Syntax
    • Parameter
    • Returns
    • Code
  • Learn Something New: How to generate a random prime number?
  • FAQs Related to Check If a Number is Prime or Not in Python
  • Conclusion
  • Trending Python Articles

Method 1: Using isprime() to check if a number is prime or not in python

1.1 Code

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

1.2 Code

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

1.3 Code

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

1.4 Code

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

Is prime number function python?

Method 2: Using if-else statements to check if a number is prime or not

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

Method 3: Using math function to check if a number is prime or not

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

Is prime number function python?

Method 4: Using sympy module to check if a number is prime or not

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

4.1 Code

import sympy
print(sympy.isprime(90))

Output

False

4.2 Code

from sympy import *
print(isprime(19))

Output

True

4.3 Code

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

Output

False

Method 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

Method 6: Using is_integer function to check if a number is prime or not

is_integer is a built-in function that is useful tos 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)

Code

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

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.

Is prime in Python function?

isprime() is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.

How do you check if it is a prime number in Python?

from math import sqrt # Number to be checked for prime n = 9 flag = 0 if(n > 1): for k in range(2, int(sqrt(n)) + 1): if (n % k == 0): flag = 1 break if (flag == 0): print(n," is a Prime Number! ") else: print(n," is Not a Prime Number! ") else: print(n," is Not a Prime Number!

Is there a function for prime numbers?

In mathematics, the prime-counting function is the function counting the number of prime numbers less than or equal to some real number x. It is denoted by π(x) (unrelated to the number π).

Is prime function Python efficient?

Function isPrime2 is faster in returning True for prime numbers. But if a number is big and it is not prime, it takes too long to return a value. First function works better with that.