Python Program to Find the Smallest Divisor of an Integer

This Python program aims to find the smallest divisor of a given integer. It prompts the user to enter an integer, calculates the smallest divisor using a function, and displays the result on the console.

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(num):
    """
    Finds the smallest divisor of a given integer.

    Args:
        num (int): The integer for which the smallest divisor needs to be found.

    Returns:
        int: The smallest divisor of the given integer.
    """

    # Checking if 1 is a divisor
    if num > 1:
        return 1

    # Finding the smallest divisor
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return i

    # If no divisor is found, the number is prime
    return num


# Prompting the user to enter an integer
num = int(input("Enter an integer: "))

# Finding the smallest divisor
result = smallest_divisor(num)

# Displaying the result
print("The smallest divisor of {} is: {}".format(num, result))

How it works

  1. The function smallest_divisor takes an integer num as input and returns the smallest divisor of num.
  2. The function checks if the input num is greater than 1. If it is, then 1 is returned since it is the smallest divisor of any number.
  3. Next, a loop is executed from 2 to the square root of num (inclusive). This loop checks if num is divisible by any number in that range.
  4. If a divisor is found, that divisor is returned as the smallest divisor.
  5. If no divisor is found in the loop, it means the number is prime, and num itself is returned as the smallest divisor.
  6. The program prompts the user to enter an integer and stores it in the variable num.
  7. It then calls the smallest_divisor function with num as the argument, and the returned value is stored in the variable result.
  8. Finally, the program displays the result by printing the smallest divisor using the print statement.

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...