Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 5 of 13
find-lcm-using-loops.py
1# Take two numbers
2a = int(input("Enter first number: "))
3b = int(input("Enter second number: "))
4
5# Find LCM
6larger = max(a, b)
7lcm = larger
8
9while True:
10 if lcm % a == 0 and lcm % b == 0:
11 break
12 lcm += larger
13
14print(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. 1

    Start lcm at the larger input.

  2. 2

    Test divisibility by both inputs.

  3. 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.