Methods to Check for Prime Numbers in Python

Methods to Check for Prime Numbers in Python

6 mins read16.3K Views Comment
clickHere
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Dec 19, 2023 11:28 IST

Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a prime number and generate the list of prime numbers in the given range. This article will discuss these methods.

A prime number is a natural number greater than 1 that has no positive divisor other than 1 and itself. In simple terms, any number that is divided by 1 and itself is referred to as Prime Number.

Example: 2, 3, 5, 7, 11, 13, 17, 19, 23,...

Note: 1 is not a prime number.

Prime Number in C: A Beginner’s Guide
Prime Number in C: A Beginner’s Guide
A prime number is a whole number that is divided by 1, and the number itself has only two factors. Non-prime numbers are called composite numbers like 4, 6, 9,...read more

Prime Number in Java: How to Check for Primality and Generate Prime Numbers
Prime Number in Java: How to Check for Primality and Generate Prime Numbers
This article will aid knowledge in your programming journey to analyze Java’s primality and prime numbers.

In Python programming, there are different methods to check whether a given number is a prime number or not.

Methods to Check Prime Numbers in Python

Method-1: Using Flag Variable

The flag variable indicates whether the number is prime or not.

Step-by-step Explanation

  • Define a function that will take one argument (the number you want to check).
  • Initialize a flag variable, i.e., set it to 'True' initially, indicating that the number is prime.
    • It will be changed to 'False' if we find a factor of the number.
  • Check if the number is less than 2, as numbers less than 2 are not prime.
  • Use a loop to check if the number has any factor other than 1 and itself. If you find a factor, set the flag to 'False' and break out the loop.
    • Based on the flag variable, return whether the number is prime or not.

Let's have a look at the Python Code. 


 
def is_prime(num):
# Initialize a flag variable
flag = True
# Numbers less than 2 are not prime
if num < 2:
flag = False
else:
# Check for factors from 2 to num-1
for i in range(2, num):
if num % i == 0:
flag = False
break
# Return the result based on the flag variable
return flag
# Example usage
number = 29
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Copy code

Method -2: Using for-else Statement


 
def is_prime(num):
# Check if the number is less than or equal to 1
# Prime numbers are greater than 1
if num <= 1:
return False # Not a prime number
# Iterate from 2 to the square root of num
# This range is sufficient to check for factors
for i in range(2, int(num**0.5) + 1):
# If num is divisible by i, then num is not a prime number
if num % i == 0:
return False # num has a divisor other than 1 and itself
# The else part of for loop is executed
# when no divisor is found in the for loop
else:
return True # num is a prime number
# Example usage
number = 29
# Check if the number is prime and print the result
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Copy code

Here, we have defined a function 'is_prime' that can take a single argument 'num' to check the primality. Initially, we will check if the num <= 1, then directly reject it (i.e., not prime). Now, we will iterate a for loop from 2 to the square root of 'num' (here, we are checking the square root because if 'num' has a factor larger than its square root, it must also have a smaller factor that we would have already checked).
Now, we will check whether num is divisible by I (num % i == 0), and if it is divisible, then num is not a prime number. Else, num is prime.
Didn't get it, don't worry!! Check out the video.

Tutorial – for Loop in Python
Tutorial – for Loop in Python
Let’s read about for Loop in Python in the below tutorial.

For Loop in Python (Practice Problem) – Python Tutorial – Shiksha Online
For Loop in Python (Practice Problem) – Python Tutorial – Shiksha Online
For loops in Python are designed to repeatedly execute the code block while iterating over a sequence or an iterable object such as a list, tuple, dictionary, or set. This...read more

The next method to check whether the given number is prime or not is using a while loop.

Method-3: Using While Loop


 
def is_prime_using_while(num):
# Prime numbers are greater than 1
if num <= 1:
return False
# Start checking from 2, since 1 is not a valid divisor for prime checking
i = 2
# Loop until i is less than or equal to the square root of num
# This is because a larger factor must be a multiple of a smaller factor
while i * i <= num:
# If num is divisible by i, it is not a prime number
if num % i == 0:
return False
i += 1 # Increment i by 1 for the next iteration
# If no divisors are found, num is a prime number
return True
# Example usage
number = 29
if is_prime_using_while(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Copy code

Python While Loop Explained With Examples
Python While Loop Explained With Examples
The while loop repeatedly executes a block of statements as long as the condition evaluates to True. Flow control is a very important feature in any programming language. The real...read more

Method -4: Using Recursion

Concept Used: Divide the number by a smaller number and see if any division results in a whole number, and if you find any such divisor (except 1), then the number is not prime.

Let's have a look at the Python code.


 
def is_prime_recursive(num, i=None):
# Initialize the divisor to num - 1 on the first call
if i is None:
i = num - 1
# Base case: if i reaches 1, the number is prime
if i == 1:
return True
# If num is divisible by any number other than 1 and itself, it's not prime
if num % i == 0:
return False
# Recursive call: check for the next smaller divisor
return is_prime_recursive(num, i - 1)
# Example usage
number = 29
if is_prime_recursive(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Copy code

Method-5: Using sympy.isprime() Function

'sympy' library in Python provides symbolic mathematical functions, including efficient methods for prime number testing. The library contains one such function, known as 'isprime(),' which is simple and straightforward and checks the primality of a given number. Let's take an example to better understand how to use 'sympy.isprime() function in Phython.


 
pip install numpy
from sympy import isprime
# Example usage of the isprime() function
# Define the number to be checked
number = 29
# Use the isprime() function from sympy to check if the number is prime
# The function returns True if the number is prime, and False otherwise
if isprime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Copy code

Conclusion

In this article, we have briefly discussed different methods to check (like flag variable, for-else statement, while loop, and sympy.isprime())  whether a given number is prime or not using Python programming with the help of examples. Hope you will like the article.

Keep Learning!!
Keep Sharing!!

FAQs on Methods to Check Prime Numbers in Python

What is a Prime Number?

A prime number is a natural number greater than 1 that has no positive divisor other than 1 and itself. In simple terms, any number that is divided by 1 and itself is referred to as Prime Number.

Example: 2, 3, 5, 7, 11, 13, 17, 19, 23,...

Is 1 a prime number or not?

No, 1 is not a prime number. A prime number is a natural number greater than 1 that has no positive divisor other than 1 and itself. In simple terms, any number that is divided by 1 and itself is referred to as Prime Number.

What are the different methods to check the prime number in Python?

There are different methods to check the prime number in Python:
1. Using Flag Variable

2. Using For-else Statement

3. Using While Loop

4. Using Recursion

5. Using sympy.isprime()

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio

Comments