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
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.