Compute the Greatest Common Divisor of Two Integers with the Euclidean Algorithm

Quick Overview

Compute the greatest common divisor of two positive integers up to one billion with the Euclidean algorithm. It tests whether you can implement the remainder loop correctly, explain why it ends with the right value, and reason about how many steps it takes.

Compute the Greatest Common Divisor of Two Integers with the Euclidean Algorithm

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given two positive integers `a` and `b`, find their greatest common divisor (GCD) using the Euclidean algorithm. The GCD of two integers is the largest positive integer that divides both numbers without leaving a remainder. ### Function Signature ```python def gcd(a: int, b: int) -> int: ``` ### Constraints - `1 <= a, b <= 10^9` ### Examples ```text Input: a = 12, b = 8 Output: 4 ``` The divisors of 12 are {1, 2, 3, 4, 6, 12} and the divisors of 8 are {1, 2, 4, 8}. The largest common divisor is 4. ```text Input: a = 54, b = 24 Output: 6 ``` Using the Euclidean algorithm: GCD(54, 24) -> GCD(24, 6) -> GCD(6, 0) = 6. Checking directly, 54 = 6 · 9 and 24 = 6 · 4, and 9 and 4 share no factor. ```text Input: a = 7, b = 20 Output: 1 ``` The first step swaps the pair: GCD(7, 20) -> GCD(20, 7) -> GCD(7, 6) -> GCD(6, 1) -> GCD(1, 0) = 1. This agrees with the fact that 7 is prime and does not divide 20.

Overview: Compute the greatest common divisor of two positive integers up to one billion with the Euclidean algorithm. It tests whether you can implement the remainder loop correctly, explain why it ends with the right value, and reason about how many steps it takes.

PracHub logo
General
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given two positive integers a and b, find their greatest common divisor (GCD) using the Euclidean algorithm.

The GCD of two integers is the largest positive integer that divides both numbers without leaving a remainder.

Function Signature

def gcd(a: int, b: int) -> int:

Constraints

  • 1 <= a, b <= 10^9

Examples

Input: a = 12, b = 8
Output: 4

The divisors of 12 are {1, 2, 3, 4, 6, 12} and the divisors of 8 are {1, 2, 4, 8}. The largest common divisor is 4.

Input: a = 54, b = 24
Output: 6

Using the Euclidean algorithm: GCD(54, 24) -> GCD(24, 6) -> GCD(6, 0) = 6. Checking directly, 54 = 6 · 9 and 24 = 6 · 4, and 9 and 4 share no factor.

Input: a = 7, b = 20
Output: 1

The first step swaps the pair: GCD(7, 20) -> GCD(20, 7) -> GCD(7, 6) -> GCD(6, 1) -> GCD(1, 0) = 1. This agrees with the fact that 7 is prime and does not divide 20.