Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Find the Smallest Divisor of an Integer
When it is required to find the smallest divisor of an integer, a simple 'for' loop is used. The smallest divisor (other than 1) is the first number that divides the given integer evenly.
Example
Below is a demonstration of finding the smallest divisor ?
first_num = int(input("Enter a number..."))
divisors = []
print("The number is")
print(first_num)
for i in range(2, first_num + 1):
if(first_num % i == 0):
divisors.append(i)
divisors.sort()
print("The smallest divisor is :")
print(divisors[0])
Output
Enter a number...56 The number is 56 The smallest divisor is : 2
Optimized Approach
The above method checks all numbers up to the input. We can optimize by stopping at the first divisor found ?
def find_smallest_divisor(num):
if num <= 1:
return None
for i in range(2, num + 1):
if num % i == 0:
return i
# Example usage
number = 56
smallest = find_smallest_divisor(number)
print(f"The smallest divisor of {number} is: {smallest}")
The smallest divisor of 56 is: 2
How It Works
The number is taken as input from the user
An empty list stores all divisors found
The range from 2 to the number is iterated over
Each number is checked using the modulo operator (%)
If the remainder is 0, the number is a divisor
All divisors are added to the list and sorted
The first element gives the smallest divisor
Key Points
Every integer has at least two divisors: 1 and itself
We start checking from 2 to find the smallest proper divisor
For prime numbers, the smallest divisor is the number itself
The optimized version stops at the first divisor found
Conclusion
Finding the smallest divisor requires checking numbers from 2 onwards using the modulo operator. The optimized approach stops at the first divisor found, making it more efficient for large numbers.
