Find HCF (GCD) Using Loops

Find HCF/GCD of two numbers using loops.

Logic BuildingIntermediate
Logic Building
# Take two numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

# Find GCD
gcd = 1
smaller = min(a, b)

for i in range(1, smaller + 1):
    if a % i == 0 and b % i == 0:
        gcd = i

print(f"GCD of {a} and {b} is {gcd}")

Output

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

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