Find LCM Using Loops
Search for the least common multiple using loops. Students test increasing multiples, use break on the first match, and note the positive-input requirement.
1# Take two numbers2a = int(input("Enter first number: "))3b = int(input("Enter second number: "))45# Find LCM6larger = max(a, b)7lcm = larger89while True:10 if lcm % a == 0 and lcm % b == 0:11 break12 lcm += larger1314print(f"LCM of {a} and {b} is {lcm}")
Output
Enter first number: 12 Enter second number: 18 LCM of 12 and 18 is 36
In this one
- Search multiples in order
- Stop on a shared multiple
- Require positive operands
How it works
- 1
Start lcm at the larger input.
- 2
Test divisibility by both inputs.
- 3
Add larger until a shared multiple triggers break.
Edge cases
What if an input is zero?
What if an input is zero?
The remainder test can raise ZeroDivisionError.
Why add larger each time?
Why add larger each time?
It skips candidates that cannot be multiples of the larger input.
What's going on
The search begins at the larger positive input. Each failure adds that same value, so every candidate is already a multiple of one input.
A candidate that divides evenly by both inputs ends the while loop. The first such candidate is the least positive common multiple. Inputs must be positive here; zero can cause modulo by zero, and negative steps do not represent this search.
What if an input is zero? The remainder test can raise ZeroDivisionError.
Why add larger each time? It skips candidates that cannot be multiples of the larger input.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What stops the search?
Pick an answer to check it.
Question 2
What if an input is zero?
Pick an answer to check it.
Questions people ask
What if an input is zero?
The remainder test can raise ZeroDivisionError.
Why add larger each time?
It skips candidates that cannot be multiples of the larger input.
What stops the search?
A candidate divisible by both inputs.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum