← Back

Home › Python programs (Hindi)

दो Numbers का GCD Python में — code, output और dry run

Read this in English

Problem statement

दो numbers का greatest common divisor निकालना — सबसे बड़ा integer जो दोनों को पूरी तरह भाग दे। GCD को HCF भी कहते हैं।

Approach 1: simple loop

Search downwards from the smaller number: the first value that divides both numbers exactly is the GCD. Simple, and it shows what "common divisor" means.

a, b = 48, 18

gcd = 1
for i in range(min(a, b), 0, -1):
    if a % i == 0 and b % i == 0:
        gcd = i
        break

print(gcd)
# Output: 6

The loop starts at min(a, b) because no divisor of both can exceed the smaller number, and it stops at the first hit — the greatest one.

Approach 2: reusable function

Euclid's algorithm is the classic: repeatedly replace the pair (a, b) with (b, a % b) until b becomes 0; the remaining a is the GCD. Dramatically faster than searching.

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

print(gcd(48, 18))   # 6
print(gcd(100, 75))   # 25
print(gcd(17, 5))     # 1 — coprime

Each step shrinks the numbers fast — the remainder is always smaller than the divisor — so even huge pairs finish in a handful of iterations.

Approach 3: Pythonic alternative

The standard library ships the algorithm: math.gcd(). There is also math.lcm() next to it for the partner concept.

import math

print(math.gcd(48, 18))          # 6
print(math.gcd(48, 18, 24))      # 6 — takes any number of arguments

Know Euclid's version by hand for exams; trust this one in real code.

Dry run

gcd(48, 18) को Euclid के loop में चलाएँ। शुरुआत: a=48, b=18। Step 1: (18, 48%18) = (18, 12)। Step 2: (12, 18%12) = (12, 6)। Step 3: (6, 12%6) = (6, 0)। b = 0 हुआ तो loop रुका, जवाब a = 6। Verify करें: 6 दोनों को बांटता है — 48 में 8 बार, 18 में 3 बार — और इससे बड़ा कोई नहीं।

Common errors

Practice on PyDebug

Concept समझने के बाद इन free problems को browser में solve करें: