Blog header background

Python Program to Check Prime Number

Updated on July 19, 2024

8 min read

Copy link
Share on WhatsApp

A prime number is a natural number greater than 1 that has no positive divisors other than 1 or itself. Prime numbers play a fundamental role in various areas of mathematics and computer science. In this post, we will create a Python program that gets the user’s input. If this number is a prime number, it will return true; otherwise, it will return false. Creating a Prime number program is good to start in Python.

What is a Prime Number?

A prime number is any natural number that is greater than 1 that has no positive divisors other than 1 and itself. In simpler terms, a prime number is a whole number greater than 1 that cannot be formed by multiplying two smaller whole numbers. For example, 2,3,5,7,11, and 13 are prime numbers. These numbers are not divided by any other number except 1 and themselves.

Prime Numbers:

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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, etc.

brochure-banner-bg

POSTGRADUATE PROGRAM IN

Multi Cloud Architecture & DevOps

Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.

Checking Prime Numbers in Python Program

In this Python program, we will check if the number is prime or not. The following program demonstrates the Python program.

Program

# Python Program

def is_prime(number):

if number <= 1:

return False

for i in range(2, int(number**0.5) + 1):

if number % i == 0:

return False


return True


userInput = input("Enter the number from user  ")

num = int(userInput)

if is_prime(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

Output

Enter the number from user  4

4 is not a prime number.

Finding Prime Number in Python using Flag Variable

In this program, we will use the flag variable to determine whether a number is prime or not. We will then print all prime numbers within a given range. In this example, we will use a loop to print the prime number.

Program

def is_prime(number):

if number <= 1:

return False

for i in range(2, int(number**0.5) + 1):

if number % i == 0:

return False

return True

start = 29

end = 100

for num in range(start, end+1):

if is_prime(num):

print(num, end=" ")

Output

29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Check the Prime Number using the Recursion

We can also find the prime number using the recursion. Recursion is the technique where we call the function itself. The following program demonstrates the Prime Number using Recursion in Python.

Program

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)

# Python Program

inputUser = input("Enter the number using the number = ")

num = int(inputUser)

if is_prime(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

Output

Enter the number using the number = 10

10 is not a prime number.
skill-test-section-bg

82.9%

of professionals don't believe their degree can help them get ahead at work.

Check the Prime Number using the while loop

In this program, we will use the while loop to check if the number is prime or not. The following program demonstrates is this number is prime or not

Program

def is_prime_while_loop(number):

if number <= 1:

return False

if number <= 3:

return True

if number % 2 == 0 or number % 3 == 0:

return False

i = 5

while i * i <= number:

if number % i == 0 or number % (i + 2) == 0:

return False

i += 6

return True

# Python Program

inputUser = input("Enter the number = ")

num = int(inputUser)

if is_prime_while_loop(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

Output

Enter the number = 2

2 is a prime number.

Check the Prime Number using the Math module

In this program, we will use the Math module to find the prime number. If the number is prime, it will return true; otherwise, it will return false.

Progame

import math

def is_prime_check_with_math(number):

if number <= 1:

return False

if number <= 3:

return True

if number % 2 == 0 or number % 3 == 0:

return False

for i in range(5, int(math.sqrt(number)) + 1, 6):

if number % i == 0 or number % (i + 2) == 0:

return False

return True

# Test the function

inputUser = input("Enter the Number from user = ")

num = int(inputUser)

if is_prime_check_with_math(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

Output

Enter the Number from user = 20

20 is not a prime number.

Check the Prime Number using the sympy.isprime() Method

In this program, we will use the sympy module. We can test whether a given number is prime or not using the sympy.isprime() function. The following program demonstrates the sympy.isPrime() method.

Program

from sympy import *


geek1 = isprime(30)

geek2 = isprime(13)

geek3 = isprime(2)


print(geek1) # check for 30 is prime or not

print(geek2) # check for 13 is prime or not

print(geek3) # check for 2 is prime or not

Output

False

True

True

Check the Prime Number using a for…else statement

In this program, we will use the for…else statement for checking the Prime Number in Python. The following program demonstrates the for ..else loop program in Python.

Program

def is_prime(num):

if num <= 1:

return False  # Not a prime number

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

return False

else:

return True


number = int(input("Enter the number = "))

if is_prime(number):

print(f"{number} is a prime number")

else:

print(f"{number} is not a prime number")

Output

Enter the number = 23

23 is a prime number

Check the Prime Number using the Trial Division Method

In this method, we will check if a number is prime by dividing it by all numbers from  2 to the square root of the number. The following program demonstrates the trial division method in the Python program.

Program

def is_prime_trial_division(number):

if number <= 1:

return False

if number <= 3:

return True

if number % 2 == 0 or number % 3 == 0:

return False

i = 5

while i * i <= number:

if number % i == 0 or number % (i + 2) == 0:

return False

i += 6

return True

# Test the function

num = int(input("Enter the Number from the User = "))

if is_prime_trial_division(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

Output

Enter the Number from the User = 2

2 is a prime number.

Check the Prime Number using a Generator Function

In this program, we will check the number using the generator function in Python language. The following program demonstrates the 10 prime numbers indefinitely.

Program

def prime_generator():

yield 2

primes = [2]

current_number = 3

while True:

is_prime = all(current_number % prime != 0 for prime in primes)

if is_prime:

primes.append(current_number)

yield current_number

current_number += 2


generator = prime_generator()

for _ in range(10):

print(next(generator))

Output

2

3

5

7

11

13

17

19

23

29

Prime Factorization

In this program, we will find the prime factorisation of a number taken from the user. The following program demonstrates the Prime factorisation.

Program

def prime_factors(n):

factors = []

divisor = 2

while n > 1:

while n % divisor == 0:

factors.append(divisor)

n //= divisor

divisor += 1

return factors

number = int(input("Enter the number from the user = "))

factors = prime_factors(number)

print(f"Prime factors of {number}: {factors}")

Output

Enter the number from the user = 15

Prime factors of 15: [3, 5]

Sieve of Eratosthenes

The sieve of Eratosthenes is an algorithm for finding a prime number at a given limit. It was developed by the Greek astronomer Eratosthenes and is a very simple algorithm for computing the prime number.

The following program demonstrates this algorithm example.

Program

def sieve_of_eratosthenes(limit):

sieve = [True] * (limit + 1)

sieve[0:2] = [False, False]

p = 2

while p * p <= limit:

if sieve[p]:

for i in range(p * p, limit + 1, p):

sieve[i] = False

p += 1

primes = [i for i, is_prime in enumerate(sieve) if is_prime]

return primes

# Find and print all prime numbers up to 50

limit = int(input("Enter the limit of the number = "))

primes = sieve_of_eratosthenes(limit)

print(f"Prime numbers up to {limit}: {primes}")

Output

Enter the limit of the number = 30

Prime numbers up to 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Conclusion

In this article, we learned various techniques to find prime numbers in the Python programming language, such as Using the Math module, the while loop, and the Sympy module. Each method has its own advantages and use cases. Prime numbers, the building blocks of number theory, hold a central position in mathematics and commute science. If you want to explore Python language, check out the Accelerator Program in Business Analytics and Data Science.

FAQs
How to print prime numbers from 1 to 100 in Python using the function?
In the Python Program, we can find the prime number between 1 and 100 using a function. This function uses a loop internally to find the prime number between 1 and 100.
What is the Python library for prime numbers?
The Python programming language includes the sympy library. In this library, we have the ‘isPrime()’ method for checking whether a number is prime or not. If this number is Prime, it will return true; otherwise, it will return false.
What is the most efficient way to find prime numbers in Python?
The most efficient way to find the prime number in Python using by algorithm like the Sieve of Eratosthenes or probabilistic prime
Are there any built-in functions in Python for finding prime numbers?
No, Python does not have a built-in function specifically for finding prime numbers. However, you can implement your own function using various algorithms.
Can a prime number be negative?
No, a Prime number must be a positive integer greater than 1 that has no positive divisors other than 1 and itself. A negative number cannot be considered a prime number.

Updated on July 19, 2024

Link
Loading related articles...