Python Program to find smallest divisor of a number

In this simple python program, we have to find the smallest divisor of a given number. It is a number-based python program, we use mod operator to find a divisor. Here we use a simple for loop and if condition to implement this program.

To understand this example, you should have knowledge of the following Python programming topics:

How to find the smallest divisor in python?

In this beginner python program, we need to find the smallest divisor of a number. The divisor is the number that can divide a number completely without any remainder. As we know any number can be divided by 1 so we are excluding 1 from the divisor list, and starting from 2 only.

For example, let us take a number 12 and the divisors of 12 are 2, 3, 4, 6, 12; from the divisors, we need to print the smallest divisor, which is 2 in this case. For a prime number like 13 17, the smallest divisor is the number itself because a prime number doesn't have divisors other than 1 and the number itself.

To apply this logic in the python programming example, we open a  for loop in python from 2 to that number and check each number in the for loop iteration using the Mod operator. After each iteration of for loop we have to check the number mod i is zero using the if condition statement in python, If we got the condition true while the iteration then print i is the smallest divisor and break the loop.


STEP 1: Accept input num from the user using the input function and convert the string to an integer using int() in python language.

STEP 2: Use a for loop from i=2 to num+1, check the user input number is divisible by i; if yes print i is the smallest divisor and break the loop


Python Source Code

                                          num=int(input("Enter a number:"))

for i in range(2,num+1):
        print("The smallest divisor is:",i)   # print the Smallest divisor


Enter a number: 15

The smallest divisor is: 3