Monday 28 December 2020

Python Program to Find the Smallest Divisor of an Integer

 This is a Python Program to find the smallest divisor of an integer.

Problem Description

The program takes in an integer and prints the smallest divisor of the integer.

Problem Solution

1. Take in an integer from the user.
2. Use a for loop where the value of i ranges from 2 to the integer.
3. If the number is divisible by i, the value of i is appended to the list.
4. The list is then sorted and the smallest element is printed.
5. Exit.

Program/Source Code

Here is the source code of the Python Program to find the smallest divisor of an integer. The program output is also shown below.

 
n=int(input("Enter an integer:"))
a=[]
for i in range(2,n+1):
    if(n%i==0):
        a.append(i)
a.sort()
print("Smallest divisor is:",a[0])
Program Explanation

1. User must enter an integer
2. The for loop ranges from 2 to the number
3. If the remainder of the number divided by the value of i is 0 that means that the element is a divisor of the number
4. The divisor of the number is then appended to the list
5. The list is then sorted and the smallest element which is the element with index 0 is printed

Runtime Test Cases
 
Case 1:
Enter an integer:75
Smallest divisor is: 3
 
Case 2:
Enter an integer:64
Smallest divisor is: 2

No comments:

Post a Comment