How to calculate the GCD (greatest common divisor) of two integers in Swift

1 Answer

0 votes
import Foundation

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(20, 12)

print("The GCD is: \(result)") 



/*
run:

The GCD is: 4

*/

 



answered Jan 19, 2025 by avibootz
...