How to Find the Smallest Divisor of a Number in Python

In this tutorial, we will learn how to program "How to Find the Smallest Divisor of a Number in Python." The objective is to find the smallest divisor of a given number. This tutorial will guide you through the process step by step, showing how to identify the smallest divisor. By the end, you will have a clear understanding of how to efficiently complete this task in Python.

This topic is straightforward to understand. Just follow the instructions I provide, and you will complete it with ease. The program I will demonstrate will show you how to get the smallest divisor. So, let’s dive into the coding process.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. while True:
  2.     print("\n============= Find the Smallest Divisor of a Number =============\n")
  3.  
  4.     n=int(input("Enter a number:"))
  5.     a=[]
  6.     for i in range(2,n+1):
  7.         if(n%i==0):
  8.             a.append(i)
  9.     a.sort()
  10.  
  11.     print("Smallest divisor is:",a[0])
  12.  
  13.     opt = input("\nDo you want to try again?(yes/no): ")
  14.        
  15.     if opt.lower() == 'yes':
  16.         ret=False
  17.     elif opt.lower() == 'no':
  18.         ret=True
  19.         print("Exiting program....")
  20.     else:
  21.         print("Please enter yes/no:")
  22.         break
  23.  
  24.     if ret == False:
  25.         continue

This Python program continuously prompts the user to enter a number and then calculates the smallest divisor of that number (excluding 1) by checking each integer from 2 up to the number itself. It adds all divisors to a list, sorts the list, and prints the first (smallest) element. After displaying the smallest divisor, the program asks the user whether they want to try again. If the user responds with "yes", the loop repeats; if they respond with "no", the program exits. Any invalid input breaks the loop with a prompt to enter a correct option.

Output:

There you have it we successfully created How to Find the Smallest Divisor of a Number in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment