How to Write a Prime Number Program in Python?

How to Write a Prime Number Program in Python?


A prime number is a natural number greater than 1 and it does not have any divisor other than 1 and itself. You can write a code in Python that will help you find all the prime numbers. In this article, we will see how to write a prime number program in Python.


So Let’s get started.
First thing First What is a Prime Number?

A prime number is a natural number greater than 1 and having no positive divisor other than 1 and itself.
For example: 3, 7, 11 etc are prime numbers as they do not have any other factors But 6 is not prime (it is composite) since, 2 x 3 = 6



Python Program to Check Prime Number

Code.............


# Program to check if a number is prime or not
num = 47
# To take input from the user
#num = int(input(“Enter a number: “))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,”is not a prime number”)
print(i,”times”,num//i,”is”,num)
break
else:
print(num,”is a prime number”)

# if input number is less than
# or equal to 1, it is not prime
else:
print(num,”is not a prime number”)


In this program, variable num is checked if it’s prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num – 1. If we find a factor in that range, the number is not prime. Else the number is prime.

We can decrease the range of numbers where we look for factors.

In the above program, our search range is from 2 to num – 1.

We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num))). The latter range is based on the fact that a composite number must have a factor less than the square root of that number. Otherwise, the number is prime.

You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.

With this, we have come to the end of our article. I hope you understood how to write a prime number program in Python.

To get in-depth knowledge of Python along with its various applications, you can enroll for live Python Certification Training with 24/7 support and lifetime access.

Drop us a Query

About the author

Bhaskar

Bhaskar

The author has a keen interest in exploring the latest technologies such as AI, ML, Data Science, Cyber Security, Guidewire, Anaplan, Java, Python, Web Designing tools, Web Development Technologies, Mobile Apps, and whatnot. He bags over a decade of experience in writing technical content.

Corporate
whatsapp arrow
Loading...
// load third party scripts onload