Skip to content

Instantly share code, notes, and snippets.

@ezefranca
Created July 26, 2024 11:18
Show Gist options
  • Save ezefranca/f8d51e7d53cc136fa6e4ed9a8dd6a2e0 to your computer and use it in GitHub Desktop.
Save ezefranca/f8d51e7d53cc136fa6e4ed9a8dd6a2e0 to your computer and use it in GitHub Desktop.
A Swift function to compute the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
/// Computes the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
/// - Parameters:
/// - a: An integer value.
/// - b: Another integer value.
/// - Returns: The greatest common divisor of `a` and `b`.
func gcd(_ a: Int, _ b: Int) -> Int {
b == 0 ? a : gcd(b, a % b)
}
// Example usage
let num1 = 48
let num2 = 18
let result = gcd(num1, num2)
print("The GCD of \(num1) and \(num2) is \(result).")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment