Technical Roadmap

Python Prime Number Program

The Logicoria Tip

A Prime Number has only 2 friends 1 and Itself. If a number has 3 friends it's not prime.

Before making a program, let's understand what a prime number is.

What is a Prime Number?

A natural number that is greater than one and has only two factors: 1 and itself.

How to know a prime number?

  • It must be a whole number greater than 0.
  • It must be greater than 1 . 1 is neither prime nor composite.
  • It is only divisible by 1 and itself.

Algorithm to check for Prime

  • Take a number as input
  • Set a count=0
  • Use a for loop to iterate from 1 to num+1 as the range function excludes the value in second parameter.
  • Use if with the modulo % operator to check if the number is completely divisible by another. If it gives a remainder of 0, then if block executes.
  • Increase the value of count by 1 every time if block executes.
  • At last use if to check the value of count variable
  • If count==2 it means it's a Prime Number otherwise not
PYTHON
num = int(input("Enter a number: "))
count = 0

# Loop to find how many numbers divide 'num' perfectly
for i in range(1, num + 1):
    if (num % i) == 0:
        count = count + 1

# checking count
if count == 2:
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Output

Enter a number: 20
20 is not a prime number.

Explanation:

  • First, we declare a variable num and take a no as input from user in it.
  • Let's take input as 20.
  • In second line we declare a count variable with initial value 0. We will use it to find the count of numbers that completely divides our input number.
  • Then we used a for loop to iterate from 1 to num+1. We put second parameter in range function as num+1 not num because by default the range functions excludes the last value.
  • Then we used if condition to check all numbers which divides our input no completely and gives 0 as remainder. Inside if we are increasing count by 1 every time our if block executes.
  • At last when the loop checks all numbers from 1 to 20 it stops. In our example of 20, the count will be 6 (because 1, 2, 4, 5, 10, and 20 divide it).
  • In next line we use another if to check count. Here if our count is exactly 2 we say it's prime. Otherwise else block executes and we get to know it is not a prime no. Here the 20 is divisible by 6 numbers the count is 6 so the else block executes and we get the output as 20 is not a prime number