DevPath

← All problems

Greatest Common Divisor

Easy math · number-theory

Description

Return the greatest common divisor of two positive integers.

Constraints

1 <= a, b

Examples

Input: a = 48, b = 36

Output: 12

Hints (1)
  • Euclid: gcd(a, b) = gcd(b, a mod b).

Solutions

Euclidean algorithm. · Time O(log min(a,b)) · Space O(1)

func gcd(a, b int) int {
    for b != 0 {
        a, b = b, a%b
    }
    return a
}

Create a free account to submit solutions, track progress and save problems.

Create account