Find HCF (GCD) Using Loops

Find HCF/GCD of two numbers using loops.

IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 4 of 13
find-hcf-gcd-using-loops.py
1# Take two numbers
2a = int(input("Enter first number: "))
3b = int(input("Enter second number: "))
4
5# Find GCD
6gcd = 1
7smaller = min(a, b)
8
9for i in range(1, smaller + 1):
10 if a % i == 0 and b % i == 0:
11 gcd = i
12
13print(f"GCD of {a} and {b} is {gcd}")

Output

Enter first number: 48
Enter second number: 18
GCD of 48 and 18 is 6

What's going on

Find largest number that divides both.

Key Concepts:

Check numbers from 1 to smaller number
If divides both, update GCD
Largest common divisor is the answer