Python Program to Check number is prime or not
In this python program, we will find whether a number is prime or not. Here we will use the if-else statement once again and the new thing we are going to use is for loop.
Here we take the modulus(%) of the given number(num variable) with every number(i variable) less than the num. And if the remainder shows 0 i.e the variable num is divided by the variable i without leaving any remainder then the variable i is the factor of the variable num and hence it prints the variable num is not a prime number and then breaks from the for loop because there is no need to check for other numbers(variable i). And if none of the numbers between the range is the factor of the variable num then it is a prime number.
Every statement is explained with use of comments.
# taking input from user num = int(input("Enter a number: ")) # the prime no. are greater than 1 if num > 1: # going through every number btw 2 and num-1 for i in range(2,num): # checking the num is divisible by i. if num % i == 0: # prints num is not a prime number print(num,"is not a prime number.") break else: # prints num is a prime number print(num,"is a prime number.") else: print(num,"is not prime number.")
15 is not a prime number.
Optimized prime number program
We are checking whether the num variable is divisible by any number between 2 and num-1. We can optimize it and check for only those numbers which are between 2 and num/2.
Hence, we just need change one statement in the program. We have to change the parameters passed inside the range function.
for i in range(2,num//2):
This way we don't have to check for unnecessary numbers.
We can optimize this program some more by taking the numbers between 2 and the square root of num (sqrt(num)). This is because a composite number(not prime) must have a factor less than the square root of that number otherwise the number is prime.
Again, we have to change the parameters passed inside the range function.
for i in range(2,math.floor(math.sqrt(num))+1):
To use the floor() and sqrt() function we have to import the math package.
Now, we know how to check whether a number is prime or not. We can use this program to print all prime numbers in an Interval.
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019