In this Python tutorial, I will explain how to create a Python Program to check Prime Numbers using different methods with illustrative examples.
Checking if a number is prime is a fundamental concept in number theory. In the world of Python, there are several methods to determine the primality of a number. Before diving into the programmatic approach, let’s understand prime numbers.
A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The first few prime numbers are 2, 3, 5, 7, 11, and so on.
For instance, 5 is prime because the only ways to write it as a product, 1 x 5 or 5 x 1, involve 5 itself. The fundamental property of primes makes them incredibly crucial in mathematics and cryptography.
To print prime numbers in Python you can read: Python program to print prime numbers [With 8 Examples]
Different Python Program to Check Prime Numbers
There are six different ways to check if the number is Prime or not in Python:
- The Basic approach- Using Flag variable
- Using Recursion
- Trial Division Method
- Using while loop
- Using the Math Module
- Using Python Libraries
Let’s see them one by one using demonstrative examples,
Method 1: Basic Python program to print prime or not
Let’s start with a simple approach. One way in Python program to check if a number is prime is to attempt dividing it by all numbers less than itself and see if any result is a whole number in Python.
For instance, At a renowned Python coding marathon in Silicon Valley, the coding platform decided to introduce a new badge called “Prime Coder” for users whose total score in all contests is a prime number. The platform uses the flag variable method in Python Program to determine if the total score is prime.
def is_prime(n):
if n <= 1:
return False
flag = True
for i in range(2, n):
if n % i == 0:
flag = False
break
return flag
scores = [101, 102, 103, 104, 105]
for score in scores:
print(f"Score {score} is prime: {is_prime(score)}")
Here, the presumption starts with a number being prime (flag set to True). It loops through numbers less than the given number in Python. If any number divides it completely, the flag is set to False, indicating it’s not prime.
Output: When calculating a user’s total score in Python, the system assumes initially (using a flag) that the score is prime. As it checks each number below the score, if any number divides the score, it updates the Python flag variable indicating the score isn’t prime. This way, only participants with prime scores earn the “Prime Coder” badge through the Python Program.
Score 101 is prime: True
Score 102 is prime: False
Score 103 is prime: True
Score 104 is prime: False
Score 105 is prime: False
This is the basic approach with flag variables in Python Program to Check Prime Numbers.
Method 2: Using recursion in a Python Program to Check Prime Number
The Python recursive function is utilized to repeatedly check divisibility. If the number is divisible by any smaller number, the function returns False. The process stops when the recursive check surpasses the square root of the number.
For instance, In Houston, a space tech startup is running simulations for rocket trajectories. They realize that specific prime trajectory values provide optimal fuel efficiency. They decided to use the recursive method in Python to check for prime values.
def is_prime(n, i=2):
if n <= 2:
return n == 2
if n % i == 0:
return False
if i * i > n:
return True
return is_prime(n, i + 1)
trajectories = [17, 18, 19, 20, 21]
for value in trajectories:
print(f"Trajectory value {value} is prime: {is_prime(value)}")
Output: Each trajectory value is processed through the Python Program, and if the value is divisible by any smaller number, the Python system discards it. Otherwise, it keeps on checking recursively until it’s confirmed that the trajectory is prime, optimizing the fuel usage for the rocket.
Trajectory value 17 is prime: True
Trajectory value 18 is prime: False
Trajectory value 19 is prime: True
Trajectory value 20 is prime: False
Trajectory value 21 is prime: False
This way we can use the recursive function in a Python program to check if a number is Prime or not.
Method 3: Trial division method in Python Program for Prime Number
This method in Python divides the number by all numbers up to its square root. The principle is: that if a number is not divisible by any number up to its square root, it won’t be divisible by bigger numbers. Efficiently determines primality by minimizing unnecessary checks.
Scenario: Denver’s municipality wants to award certain homes with tax deductions if their house number is prime. They chose the trial division method to validate prime house numbers through Python.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
houses = [1009, 1010, 1011, 1012, 1013]
for house in houses:
print(f"House number {house} is prime: {is_prime(house)}")
Output: To determine which houses get the tax deduction through Python, they only check for divisibility up to the square root of the house number. This ensures quicker processing and faster results in determining prime numbers in Python.
House number 1009 is prime: True
House number 1010 is prime: False
House number 1011 is prime: False
House number 1012 is prime: False
House number 1013 is prime: True
This way, the trial division method works in Python to check if the number is Prime or not.
Method 4: While loop in the Python Program To Check Whether The Number Is Prime Or Not
Instead of a for loop, this Python method leverages a while loop for divisibility checks. The loop runs until the square of the iterating value becomes greater than the number in question. It offers a slightly different Python loop control while checking for primality.
Scenario: An indie game developer in Miami introduces a feature in his game: if a player’s score is a prime number, they get a special bonus item. The Python developer uses the while loop method to ascertain if the score is prime.
def is_prime(n):
if n <= 1:
return False
i = 2
while i*i <= n:
if n % i == 0:
return False
i += 1
return True
scores = [89, 90, 91, 92, 93]
for score in scores:
print(f"Player score {score} is prime: {is_prime(score)}")
Output: For each score achieved by a player, the game system in Python continuously checks, using a while loop, if the score is divisible by any smaller number. If it finds any such number, it breaks out of the loop. Otherwise, it awards the player the bonus item.
Player score 89 is prime: True
Player score 90 is prime: False
Player score 91 is prime: False
Player score 92 is prime: False
Player score 93 is prime: False
The while loop in Python can also be used to check if the number is Prime.
Method 5: Python Program to Check a Number is Prime or Not using a math module
The Math module in Python provides the sqrt() function which returns the square root of a specified number. This method involves dividing the number by all numbers up to its square root, similar to the trial division but in a more Pythonic manner. It efficiently establishes the primality of a number by reducing computational overhead.
For example, In the tech hub of San Francisco, a weather prediction company finds that certain prime-numbered data points correlate with accurate weather predictions. They use the Python math module method to filter prime numbers.
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
data_points = [11, 12, 13, 14, 15]
for point in data_points:
print(f"Data point {point} is prime: {is_prime(point)}")
Output: Whenever they collect data, they utilize Python math.sqrt() function to efficiently check for prime data points. This way, they only focus on the most accurate and relevant data points for their predictions, enhancing the overall accuracy of their weather models.
Data point 11 is prime: True
Data point 12 is prime: False
Data point 13 is prime: True
Data point 14 is prime: False
Data point 15 is prime: False
The Math module in Python Program can be used to check Prime number.
Method 6: Python Program to check prime numbers using Python libraries
Python has libraries like sympy which provides built-in methods like isprime() for checking prime numbers. This is efficient and can be useful for quick implementations.
For instance, In cryptographic systems, the difficulty in factorizing large numbers into their prime constituents lends an added layer of security. This is the foundation behind RSA encryption, one of the widely used public-key cryptosystems. The startup needs to frequently check for the primality of large numbers to enhance their encryption through Python.
Using the sympy library, they can easily check prime number program in Python:
from sympy import isprime
number = 32416190071
if isprime(number):
print(f"{number} can be used for encryption!")
else:
print(f"{number} is not suitable for the encryption process.")
Output: The isprime() function from sympy library, allows them to quickly determine if a number is prime in Python, providing a foundational building block for their encryption mechanisms.
32416190071 can be used for encryption!
This way we can use sympy Python library in the Program to check prime or not.
Note: Install sympy package in Python to use this method.
More Advanced Methods
There are many sophisticated algorithms to determine prime numbers, such as the Sieve of Eratosthenes, the Miller-Rabin primality test, and others. These algorithms are beyond the scope of this article but are essential for determining large prime numbers used in real-world applications like RSA encryption.
Conclusion
In this article, we learned how to create a Python Program to check Prime Numbers. We started with a basic method and then introduced a more efficient approach such as recursion, Trial division, while loop, math module, or sympy Python library. Using our example, we demonstrated how to apply this knowledge in real-world scenarios.
Whether we’re interested in mathematical concepts or practical applications, prime numbers offer a fascinating area of study.
You may also like to read:
- Python program to print prime numbers [With 8 Examples]
- How to generate 10 digit random number in Python?
- How to find perfect number in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.