Checking prime numbers is one of the most common questions asked in college practices so in this post, we will learn different ways to check prime number in Python with detailed explanations and examples.
But before we jump into the programming part let’s understand the basics first.
What is Prime Numbers?
A natural number that is only divisible by one and itself is known as a prime number. For example 2,3,5,7,11,13,17,19.. etc are prime numbers.
After understanding prime numbers, now let’s jump into the programming part and learn different methods to check prime numbers in Python.
Method-1: Check Prime Number Using For Loop
Before writing this program few programming concepts you have to Know:
Algorithm
- Take input From the User (
num
). - Create one variable
flag
and initialize it with zero (flag = 0
). - Using for-loop iterate from 2 to
num-1
(for i in range(2, num)
). - Inside for-loop check
if num % i == 0
then doflag = 1
andbreak
the loop. - Outside of for-loop check
if flag == 1 or num == 1
then print the given number is not primeelse
given number is prime.
Source Code
num = int(input("Enter a number: "))
flag = 0
for i in range(2,num):
if num % i == 0:
flag = 1
break
if flag == 1 or num == 1:
print(f"{num} is not prime number")
else:
print(f"{num} is prime number")
Output
Enter a number: 5
5 is prime number
Method-2: Check Prime Number Using While Loop
Before writing this program few programming concepts you have to Know:
NOTE: In the case of a while-loop, we use the same algorithm as above. The only difference is that, instead of a for-loop, we use a while-loop.
Source Code
num = int(input("Enter a number: "))
flag = 0
i = 2
while i < num:
if num % i == 0:
flag = 1
break
i+=1
if flag == 1 or num == 1:
print(f"{num} is not prime number")
else:
print(f"{num} is prime number")
Output
Enter a number: 9
9 is not prime number
Method-3: Check Prime Number Using Function
Before writing this program few programming concepts you have to Know:
Algorithm
- Define a function (
def check_prime(n)
). - Check
if n < 2
then returnFalse
(which means number is not prime). - Outside of the if statement, using for-loop iterate from 2 to
n-1
(for i in range(2, n)
) - Inside for loop check
if n % i == 0
then returnFalse
. - Outside of the for loop return
True
(which means the number is prime).
Source Code
def check_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True # If no divisor is found, the number is prime
num = int(input("Enter a number: "))
if check_prime(num):
print(f"{num} is Prime number")
else:
print(f"{num} is not Prime number")
Output
Enter a number: 11
11 is Prime number
This is all about how we can check prime number in Python. I hope this article adds some value to your life – thank you.