Prime number

A prime number is an integer which is greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

The logic to check a number is prime or not is really simple. We only need to check if the given number is completely divisible by any other smaller number or not, but not by 1 and itself.

After taking input from the user, we have to run one loop up to half of the given number. Now the reason for running one loop up to half of the given number is because we know, a number can only be divisible by a number which is lesser than its half.

Inside the loop we have to check if the given number “num” is completely divisible by current number “i” or not, If yes then set the value of the variable i to num and terminate the loop here, if no then continue the loop.

Once the loop is completed or terminated control comes out of the loop, here we have to check if the value of the variable i is equivalent to the given number or not. If yes then it is not a Prime number otherwise it is a prime number.

Program

# Take input from user
num = int(input("Enter any number : "))

i = 1

# Check for prime
for i in range(2, num):
    if (int(num % i) == 0):
        i = num
        break;

if i is num:
    print("\n" + str(num), "is not a prime number.")
else:
    print("\n" + str(num), "is a prime number.")

Output

Enter any number : 7
7 is a prime number.