Sobes.tech
Junior — Middle

Milliste andmete või struktuuridega töötab suurima ühise jagaja (GCD) otsingualgoritm?

sobes.tech AI

Vastus AI-lt

The greatest common divisor (GCD) algorithm operates on integers. The main data are two integers, for which the maximum divisor that divides both numbers without remainder needs to be found.

Most commonly, the Euclidean algorithm is used, which repeatedly replaces the pair of numbers with (b, a % b) until the remainder becomes zero. In the end, the last non-zero divisor remains — this is the GCD.

Example in Swift:

func gcd(_ a: Int, _ b: Int) -> Int {
    var a = a
    var b = b
    while b != 0 {
        let temp = b
        b = a % b
        a = temp
    }
    return a
}

let result = gcd(48, 18) // result will be 6