For working professionals
For fresh graduates
More
Prime numbers are fascinating! They are natural numbers greater than 1 that can't be divided by anything other than 1 and themselves. These unique numbers play a vital role in math and are especially important in fields like computer science and cryptography.
Learning to identify prime numbers is more than just a classroom exercise; it has practical uses in our daily lives. Prime numbers help secure online communications through encryption, improve search algorithms, and even generate random numbers for simulations.
If you're interested in programming, Python makes it easy to check whether a number is prime. You can use simple loops or advanced library functions like `sympy.isprime()`. With all the tools and methods available in Python, both beginners and seasoned pros can tackle primality tests with ease.
In this article, we’ll explore different techniques for checking prime numbers in Python, complete with practical examples, performance insights, and real-world applications. Let’s dive in and discover the world of prime numbers together!
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
def is_prime(number):
"""
Check if a given number is prime using for-else statement.
Args:
number (int): The number to be checked for primality.
Returns:
bool: True if the number is prime, False otherwise.
"""
# Handle special cases
if number < 2:
return False
# Check for divisibility from 2 to the square root of the number
for divisor in range(2, int(number**0.5) + 1):
# If number is divisible by any divisor, it's not prime
if number % divisor == 0:
return False
else:
# This block executes only if no divisors are found
return True
# Test the function with different numbers
test_numbers = [2, 3, 4, 5, 7, 11, 12, 17, 20, 29]
print("Prime Number Checker Results:")
for num in test_numbers:
result = is_prime(num)
print(f"{num} is {'prime' if result else 'not prime'}")
Output
Prime Number Checker Results:
2 is prime
3 is prime
4 is not prime
5 is prime
7 is prime
11 is prime
12 is not prime
17 is prime
20 is not prime
29 is prime
Explanation of Code
Key Points About the For-Else Mechanism
Related Reads:
def is_prime(number):
# Check if the number is less than 2
# Numbers less than 2 are not prime
if number < 2:
return False
# Initialize the flag as True
# We assume the number is prime until proven otherwise
is_prime_flag = True
# Check for divisors from 2 to the square root of the number
# We only need to check up to square root for efficiency
for i in range(2, int(number**0.5) + 1):
# If the number is divisible by any value, it's not prime
if number % i == 0:
# Set the flag to False
is_prime_flag = False
# Exit the loop as soon as a divisor is found
break
# Return the final state of the flag
return is_prime_flag
# Test the function with different numbers
test_numbers = [2, 3, 4, 5, 7, 10, 11, 13, 17, 20]
# Print primality of each number
for num in test_numbers:
print(f"{num} is {'prime' if is_prime(num) else 'not prime'}")
Output
2 is prime
3 is prime
4 is not prime
5 is prime
7 is prime
10 is not prime
11 is prime
13 is prime
17 is prime
20 is not prime
Explanation of Code
Initial Check
Flag Initialization
Divisibility Check
Flag Modification
Result Return
Key Advantages of Flag Variable
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
def is_prime(number):
# Handle edge cases
if number < 2:
return False
# Check for divisibility from 2 to square root of the number
for i in range(2, int(number**0.5) + 1):
# If number is divisible by any value, it's not prime
if number % i == 0:
# Break the loop as soon as a divisor is found
break
# If no divisor found, continue checking
continue
else:
# If loop completes without finding divisors, number is prime
return True
# If loop breaks due to finding a divisor, number is not prime
return False
# Test the function with various numbers
test_numbers = [2, 3, 4, 5, 7, 10, 11, 13, 17, 20]
print("Prime Number Checking Results:")
for num in test_numbers:
result = is_prime(num)
print(f"{num} is {'prime' if result else 'not prime'}")
Output
Prime Number Checking Results:
2 is prime
3 is prime
4 is not prime
5 is prime
7 is prime
10 is not prime
11 is prime
13 is prime
17 is prime
20 is not prime
Explanation of Code
Related Read:
def is_prime(number):
# Check if the number is less than 2 (not prime)
if number < 2:
return False
# Initialize the divisor
divisor = 2
# Use while loop to check divisibility
while divisor * divisor <= number:
# Check if the number is divisible by the current divisor
if number % divisor == 0:
# If divisible, it's not a prime number
return False
# Increment the divisor
divisor += 1
# If no divisors found, the number is prime
return True
# Test the function
test_numbers = [2, 3, 4, 5, 7, 10, 11, 13, 17, 20]
# Print prime status for each number
for num in test_numbers:
if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Output
2 is a prime number
3 is a prime number
4 is not a prime number
5 is a prime number
7 is a prime number
10 is not a prime number
11 is a prime number
13 is a prime number
17 is a prime number
20 is not a prime number
Explanation of Code
Function Definition
Initial Check
While Loop Mechanism
Divisibility Check
Divisor Increment
Prime Confirmation
Related Read
import math
def is_prime_using_math(number):
"""
Check if a given number is prime using the math module.
A prime number is a natural number greater than 1 that is only divisible by 1 and itself.
This method uses mathematical properties to efficiently check primality.
"""
# Handle special cases
if number <= 1:
return False
# 2 is the only even prime number
if number == 2:
return True
# Even numbers greater than 2 are not prime
if number % 2 == 0:
return False
# Use math.isqrt to find the integer square root efficiently
# We only need to check divisors up to the square root of the number
sqrt_number = math.isqrt(number)
# Check for divisibility by odd numbers up to the square root
for divisor in range(3, sqrt_number + 1, 2):
# If the number is divisible by any odd number, it's not prime
if number % divisor == 0:
return False
# If no divisors are found, the number is prime
return True
# Example usage and demonstration
def demonstrate_prime_checking():
# List of numbers to test
test_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 19, 20, 29]
print("Prime Number Checking Results:")
print("-" * 30)
for num in test_numbers:
result = is_prime_using_math(num)
print(f"{num} is {'prime' if result else 'not prime'}")
# Run the demonstration
demonstrate_prime_checking()
Output
Prime Number Checking Results:
------------------------------
1 is not prime
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
11 is prime
12 is not prime
13 is prime
17 is prime
19 is prime
20 is not prime
29 is prime
Explanation
def is_prime_recursive(n, divisor=None):
"""
Check if a number is prime using recursive approach
Args:
n (int): The number to check for primality
divisor (int, optional): The current divisor to check against.
Defaults to None for initial call.
Returns:
bool: True if the number is prime, False otherwise
"""
# Handle special cases
if n <= 1:
return False
# If no divisor specified, start with square root of n
if divisor is None:
divisor = int(n ** 0.5)
# Base cases
# If we've checked all potential divisors successfully, the number is prime
if divisor == 1:
return True
# If the number is divisible, it's not prime
if n % divisor == 0:
return False
# Recursively check with the next lower divisor
return is_prime_recursive(n, divisor - 1)
# Test the function with different numbers
test_numbers = [2, 3, 4, 7, 10, 17, 20, 29]
print("Prime Number Recursion Test Results:")
for num in test_numbers:
result = is_prime_recursive(num)
print(f"{num} is {'prime' if result else 'not prime'}")
Output
Prime Number Recursion Test Results:
2 is prime
3 is prime
4 is not prime
7 is prime
10 is not prime
17 is prime
20 is not prime
29 is prime
Explanation
The recursive approach to checking prime numbers involves systematically testing potential divisors from the square root of the number down to 1. Instead of using a loop, we use recursive function calls to check divisibility.
Key Recursive Strategy:
Code Breakdown:
Recursion Logic:
Step-by-Step Explanation:
Related Read:
pip install sympy
# Import the isprime function from sympy library
from sympy import isprime
# Function to demonstrate prime number checking
def check_prime_numbers():
# Test various numbers to demonstrate isprime() functionality
test_numbers = [2, 7, 10, 17, 20, 29, 100, 997]
# Iterate through each number and check its primality
for number in test_numbers:
# Use isprime() to determine if the number is prime
if isprime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
# Call the function to run the demonstration
check_prime_numbers()
Output
2 is a prime number.
7 is a prime number.
10 is not a prime number.
17 is a prime number.
20 is not a prime number.
29 is a prime number.
100 is not a prime number.
997 is a prime number.
Explanation of Code
Import the Method:
Function Creation:
Number Selection:
Primality Testing:
Method Advantages:
# Large number primality test
large_number = 104729
print(f"{large_number} is prime: {isprime(large_number)}")
# Interactive user input
def interactive_prime_check():
try:
number = int(input("Enter a number to check if it's prime: "))
if isprime(number):
print(f"{number} is a prime number!")
else:
print(f"{number} is not a prime number.")
except ValueError:
print("Please enter a valid integer.")
Output
104729 is prime: True
Method | Time Complexity | Space Complexity | Use Case |
If-Else/For-Else | O(sqrt(n)) | O(1) | Suitable for small inputs. |
Flag Variable | O(sqrt(n)) | O(1) | Beginner-friendly approach. |
Break and Continue | O(sqrt(n)) | O(1) | Reduces unnecessary checks. |
While Loop | O(sqrt(n)) | O(1) | Useful when loop iteration is required. |
Math Module | O(sqrt(n)) | O(1) | Enhances precision for large numbers. |
Recursion | O(sqrt(n)) | O(n) (stack memory) | For functional programming enthusiasts. |
sympy.isprime() | O(sqrt(n)) to O(log(n)^3) | O(1) | Best for large datasets and performance. |
Note: The complexity of sympy.isprime() varies based on its internal optimizations for small and large numbers.
Related Read:
With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Python courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.
By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.
So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.
Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:
Similar Reads: Top Trending Blogs of Python
To determine if a number is prime in Python, you must check whether it is divisible only by 1 and itself. A basic method involves iterating through potential divisors up to the square root of the number. If no divisors are found, the number is considered prime. More efficient methods reduce the number of iterations by skipping even numbers and known multiples of smaller primes.
There is no single formula to find all prime numbers, but algorithms like the Sieve of Eratosthenes efficiently identify primes up to a certain range by systematically eliminating multiples of each prime starting from 2. For individual numbers, divisibility checks are performed, often combined with mathematical optimizations such as checking divisors only up to the square root of the number.
Prime numbers from 0 to 100 include:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.
To check wheteher the given number is prime or not, you can use methods like:
Generating prime numbers can be done in two ways:
Using a function to check for prime numbers promotes reusability and clarity. The function takes a number as input and returns whether it’s prime. Functions can also encapsulate optimizations, like reducing the number of checks by skipping even numbers or iterating only up to the square root of the input. Check the blog to get more details.
To check the prime number in python, you can use the math module or sympy.isprime() function.
The fastest way to check for primality depends on the number size:
Ready to challenge yourself? Take our Free Python Quiz!
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.