Before going to the program for Prime Number or Not first let us understand what is a Prime Number?
A Prime Number is a number greater than 1 and which is only divisible by 1 and the number itself.
17 is a Prime Number because 17 is not divisible by any number other than 1 and 17.
To find whether a Number is Prime Number or Not it is enough to check whether ‘n’ is divisible by any number between 2 and √n. If it is divisible then ‘n’ is not a Prime Number otherwise it is a Prime Number.
Related: C Program to display Prime Numbers between Two Intervals
Program code for Prime Number or Not in Python:
# Python Program to check if a number is prime or not from math import sqrt # To take input from the user num = int(input("Enter a number: ")) # define a flag variable prime_flag = False # prime numbers are greater than 1 if num > 1: for i in range(2, int(sqrt(num)) + 1): if (num % i) == 0: prime_flag = True break # check if flag is True if prime_flag: print(num, "is not a prime number") else: print(num, "is a prime number")
Related: Prime number or Not in C++ using While Loop
- First, the computer reads the positive integer value from the user.
- Then using for loop it checks whether ‘n’ is divisible by any number between 2 and √n.
- Finally, the if else condition is used to print whether the number is a prime number or not.