Algorithm
- Initialize: Set the variable
is_prime
toTrue
. - Special Cases:
- If the number is less than or equal to 1, set
is_prime
toFalse
. - If the number is 2, it's a prime number, so no further checks are needed.
- If the number is even (other than 2), set
is_prime
toFalse
. - Divisibility Check:
- Iterate from 3 to the square root of the number (inclusive).
- If the number is divisible by any of these values, set
is_prime
toFalse
. - Result:
- If
is_prime
is stillTrue
after the above checks, the number is prime.
- If
Code Examples
#1 Example- Python Programing Prime Number in Python using For Loop
Code -
Python Programming
# Prime Number Program in Python using For Loop
a=int(input("Enter number: "))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print("Number is prime")
else:
print("Number isn't prime">
Copy The Code &
Try With Live Editor
Input
Enter number: 7
Output
Number is prime
#2 Example- Python programing Prime Number Program in Python using Recursion
Code -
Python Programming
def check(n, div = None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print("Number not prime")
return False
else:
return check(n, div-1)
else:
print("Number is prime")
return 'True'
n=int(input("Enter number: "))
check(n)
Copy The Code &
Try With Live Editor
Input
1. Enter number: 13
2. Enter number: 30
2. Enter number: 30
Output
1. Number is prime
2. Number not prime
2. Number not prime
#3 Example- Python Programing Prime Number Program in Python using Recursion
Code -
Python Programming
r=int(input("Enter upper limit: "))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a>
Copy The Code &
Try With Live Editor
#4 Example- Python Programing Prime Number Program in Python using Sieve of Eratosthenes
Code -
PHP Programming
n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
prime=min(sieve)
print(prime,end="\t")
sieve-=set(range(prime,n+1,prime))
print()
Copy The Code &
Try With Live Editor
Demonstration
Python Programing Example to Check Prime Number-DevsEnv