Python Program to Find the Smallest Divisor of an Integer

In this program, we will write a Python code to find the smallest divisor of a given integer. The divisor is a number that divides another number without leaving a remainder. We will use a brute-force approach to find the smallest divisor by iterating through all numbers starting from 2 and checking if they evenly divide the given integer.

Problem Statement

Write a Python program to find the smallest divisor of a given integer.

Python Program to Find the Smallest Divisor of an Integer

def smallest_divisor(n):
    """
    Function to find the smallest divisor of a given integer.
    """
    # Check if the number is less than 2
    if n < 2:
        return None
    
    # Iterate through all numbers starting from 2
    for i in range(2, int(n**0.5) + 1):
        # Check if i is a divisor of n
        if n % i == 0:
            return i
    
    # If no divisor is found, the number itself is the smallest divisor
    return n


# Get user input
num = int(input("Enter an integer: "))

# Find the smallest divisor
result = smallest_divisor(num)

# Print the result
if result is None:
    print("No smallest divisor exists for the given number.")
else:
    print(f"The smallest divisor of {num} is {result}.")

How it works

  1. The function smallest_divisor takes an integer n as input and returns the smallest divisor of that number.
  2. It first checks if the number is less than 2. If it is, the function returns None as there is no divisor less than 2 for any number.
  3. It then iterates through all numbers starting from 2 up to the square root of n (rounded up to the nearest integer).
  4. For each number i, it checks if i is a divisor of n by using the modulo operator (%). If n is divisible by i, it means i is the smallest divisor of n, and the function returns i.
  5. If no divisor is found in the previous step, it means that the number itself is the smallest divisor, and the function returns n.
  6. In the main program, the user is prompted to enter an integer.
  7. The smallest_divisor function is called with the user input as the argument, and the result is stored in the result variable.
  8. Finally, the program checks if the result is None (indicating no smallest divisor) and prints the appropriate message. Otherwise, it prints the smallest divisor found.

Input / Output

Python Program to Find the Smallest Divisor of an Integer

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...