Write a program to find LCM of the given numbers using for/while.
Code:
def find_lcm_for(num1, num2):
# Find the maximum of the two numbers
max_num = max(num1, num2)
# Start from the maximum number and check multiples until finding the LCM
for lcm in range(max_num, num1 * num2 + 1, max_num):
if lcm % num1 == 0 and lcm % num2 == 0:
return lcm
# Prompt the user to enter two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Call the function to find LCM using for loop
lcm = find_lcm_for(num1, num2)
print("LCM of", num1, "and", num2, "is:", lcm)
print("Using While Loop")
def find_lcm_while(num1, num2):
# Find the maximum of the two numbers
max_num = max(num1, num2)
# Initialize LCM as the maximum number
lcm = max_num
# Start from the maximum number and check multiples until finding the LCM
while True:
if lcm % num1 == 0 and lcm % num2 == 0:
return lcm
lcm += max_num
# Prompt the user to enter two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Call the function to find LCM using while loop
lcm = find_lcm_while(num1, num2)
print("LCM of", num1, "and", num2, "is:", lcm)
0 Comments