Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors


This Python code defines a function find_smallest_multiple(n) that calculates the smallest multiple of the first n positive integers and returns both the smallest multiple and its prime factors. Here's an explanation of each part of the code:

  • def find_smallest_multiple(n): This line defines a function called find_smallest_multiple that takes an integer n as its argument.
  • if n < 1:: This line checks if n is less than 1, and if so, it returns None, indicating an invalid input.
  • factors = []: This line initializes an empty list called factors to store the prime factors of the smallest multiple.
  • multiple = 1: This line initializes the variable multiple to 1, which will be used to calculate the smallest multiple.
  • The code uses a for loop to iterate through numbers from 2 to n (inclusive).
  • Inside the loop, it checks if multiple is not divisible by i. If this condition is met, it means that i is a prime factor of the multiple. The code then enters a nested loop to handle cases where i has multiple occurrences in the prime factorization.
  • After updating the multiple and factors lists, the loop continues with the next number.
  • Finally, the function returns a tuple containing the multiple (smallest multiple) and the factors (prime factors).
  • Outside the function, the code prompts the user to enter a positive integer n.
  • It calls the find_smallest_multiple function with n as the argument and stores the result in the result variable.
  • If the result is not None (indicating a valid input), it prints the smallest multiple and its prime factors. Otherwise, it prints an error message for invalid input.

Source Code

def find_smallest_multiple(n):
    if n < 1:
        return None
 
    factors = []
    multiple = 1
 
    for i in range(2, n + 1):
        if multiple % i != 0:
            for j in factors:
                if i % j == 0:
                    i //= j
            multiple *= i
            factors.append(i)
 
    return multiple, factors
 
n = int(input("Enter a positive integer (n): "))
 
result = find_smallest_multiple(n)
 
if result:
    multiple, factors = result
    print(f"The smallest multiple of the first {n} numbers is: {multiple}")
    print(f"Factors of the smallest multiple: {factors}")
else:
    print("Invalid input. Please enter a positive integer greater than 0.")
 

Output

Enter a positive integer (n): 6
The smallest multiple of the first 6 numbers is: 60
Factors of the smallest multiple: [2, 3, 2, 5]

Example Programs