Python Program to Find the Smallest Divisor of an Integer

1. Introduction

In this tutorial, we will learn how to write a Python program to find the smallest divisor of an integer.

The smallest divisor of an integer is the least integer greater than 1 that divides the number without leaving a remainder. In essence, it is the smallest number that you can multiply by another integer to reach the number in question.

2. Program Steps

1. Accept or define an integer to find its smallest divisor.

2. Initialize a variable to start from the smallest possible divisor (2, since 1 divides everything).

3. Incrementally check each number from 2 onwards to see if it divides the integer without leaving a remainder.

4. Once the smallest divisor is found, stop the search and return this divisor.

3. Code Program

# Function to find the smallest divisor of an integer
def find_smallest_divisor(n):
    # Start checking from 2, since 1 divides everything
    for i in range(2, n + 1):
        # If i divides n without a remainder, it is the smallest divisor
        if n % i == 0:
            return i
    # If no divisor is found, return n (means it is a prime number)
    return n

# Number to find the smallest divisor of
number = 49
# Call the function and print the smallest divisor
print(find_smallest_divisor(number))

Output:

7

Explanation:

1. find_smallest_divisor is a function defined with n, the target integer, as its parameter.

2. A loop starts at 2, because every integer is divisible by 1, and the task is to find the smallest divisor greater than 1.

3. The loop checks each number i to see if it divides n with no remainder using n % i == 0.

4. If such an i is found, it is immediately returned as it will be the smallest divisor due to the incremental nature of the loop.

5. If the loop completes without finding a divisor, which means n is prime, n itself is returned.

6. When find_smallest_divisor is called with number set to 49, it returns 7, which is the smallest divisor of 49.

Comments