Methods to Check for Prime Numbers in Python

Methods to Check for Prime Numbers in Python

8 mins read16.3K Views 2 Comments
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Oct 7, 2024 08:55 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.

methods to check prime number in python

Table of Content

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.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
โ€“ / โ€“
3 months
โ€“ / โ€“
2 weeks
โ€“ / โ€“
16 weeks
โ‚น1.7 K
3 months
โ€“ / โ€“
โ€“ / โ€“
โ‚น4.24 K
2 weeks
โ‚น3 K
3 weeks
โ€“ / โ€“
4 months

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. Let's help you learn about Prime numbers that can only be divisible by 1...read more

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). If it is, then num is not a prime number. Otherwise, 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
For Loop in Python (Practice Problem) โ€“ Python Tutorial
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.The while loop repeatedly executes a block of statements as long as the condition...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()

How can I check if a number is prime using a simple loop in Python?

You can use a basic loop to check for prime numbers by iterating from 2 to the square root of the number and checking for factors.

import math

def is_prime_simple(n):
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

# Example usage
print(is_prime_simple(29))  # Output: True
print(is_prime_simple(15))  # Output: False

How can I use a list comprehension to check for a prime number in Python?

List comprehension can be utilized to check for factors in a concise way.

def is_prime_list_comp(n):
    if n <= 1:
        return False
    return all(n % i != 0 for i in range(2, int(n ** 0.5) + 1))

# Example usage
print(is_prime_list_comp(29))  # Output: True
print(is_prime_list_comp(15))  # Output: False

How can I check for prime numbers using the Sieve of Eratosthenes in Python?

The Sieve of Eratosthenes is an efficient algorithm to find all primes up to a given limit.

def sieve_of_eratosthenes(limit):
    primes = [True] * (limit + 1)
    p = 2
    while p * p <= limit:
        if primes[p]:
            for i in range(p * p, limit + 1, p):
                primes[i] = False
        p += 1
    prime_numbers = [p for p in range(2, limit + 1) if primes[p]]
    return prime_numbers

# Example usage
print(sieve_of_eratosthenes(30))  # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

How can I use recursion to check if a number is prime in Python?

A recursive function can be used to check for prime numbers by testing divisibility.

def is_prime_recursive(n, divisor=None):
    if n <= 1:
        return False
    if divisor is None:
        divisor = n - 1
    if divisor == 1:
        return True
    if n % divisor == 0:
        return False
    return is_prime_recursive(n, divisor - 1)

# Example usage
print(is_prime_recursive(29))  # Output: True
print(is_prime_recursive(15))  # Output: False

How can I check if a number is prime using the sympy library in Python?

The sympy library provides a built-in function to check for prime numbers efficiently.

from sympy import isprime

# Example usage
print(isprime(29))  # Output: True
print(isprime(15))  # Output: False

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

(2)

If you are suspecting that your husband is having an affair and he communicates with the person on his phone, you need to monitor his iPhone with the help of Tomcyberghost @ gmail com If he thinks that his phone cannot be tracked because it is an iPhone then he is wrong. TOMCYBERGHOST can give you a

Reply to Florence Jenny

you have told in above content that we can check prime number with Using Flag Variable Using for-else Statement Using While Loop Using Recursion Using sympy.is prime () Method these methods but I have made a programme in which are checking number is prime or not only with if else a=int (input ("Ent

Reply to Gautam Sharma

a=int (input ("Enter your number") if a=2 or a=3 or a=7 or a=5: print ("it is a prime number") elif a=1 : print ("it is not a prime number it is unique number") elif a%2=0 or a%3=0 or a%5=0 or a%7=0: print ("it is not a prime number") elif a/a=1 and a%1=0: print ("it is a prime number") else:

...more