Python Practice › Basic Programs › Program 36

HCF (GCD) of two numbers

EasyBasic Programs · 36 of 40

Write a Python program to find the HCF (highest common factor, also called GCD) of two numbers.

Advertisement
Input
48 and 36
Output
HCF: 12

Approach

  1. Euclid’s algorithm: replace (a, b) with (b, a % b) until b is 0; then a is the HCF.

Solution 1: Euclid’s algorithm

Python
a, b = 48, 36while b:    a, b = b, a % bprint("HCF:", a)
Output
HCF: 12

Line by line

Line 2

The loop runs while b is not zero.

Line 3

(48, 36) → (36, 12) → (12, 0), so the HCF is 12.

Solution 2: math.gcd

Python
import mathprint(math.gcd(48, 36))
Output
12
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs