Python Program to find smallest divisor of a number using sort

In this simple python program, we have to sort and find the smallest divisor from a list. It's an array-based python program.

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

How to sort and find the smallest divisor from a list in python?

In this beginner python program, we need to find the smallest divisor of a number. The divisor is the number that is divisible by the given number. For example, let us take a number, 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. 

To apply this logic in a 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 and append the divisors into a list using append() the method. After we will have a  python list of divisors, Now apply the sort() function on the list to sort the list in ascending order. 

NOTE:  Sort() function in python will sort the list in ascending order as default. To do the sort in descending order, we use them reverse in the sort function. 


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

STEP 2: Initialize the list using python basic syntax.

STEP 3: Use a for loop from 2 to the number to check each number which is divisor or not.

STEP 4: Use an if condition and mod operator to check if it is a perfect divisor or not and append to a list if it is a divisor using append() method in python.

STEP 5: Apply the list sort function to get the python list sorted in ascending order.

STEP 6: Print the element in the position list[0] as it will be is the lowest divisor of the number.

Python Source Code

                                          n=int(input("Enter an number:"))


for i in range(2,n+1):


        a.append(i)    # add the divisors to a list

a.sort()    # sort the list

print("Smallest divisor is:",a[0])   # print the first element in the list


Enter an number: 15

Smallest divisor is: 3