Skip to content

Instantly share code, notes, and snippets.

@aniltv06
Created August 22, 2018 05:53
Show Gist options
  • Save aniltv06/6f3e9c6208e27a89259919eeb3c3d703 to your computer and use it in GitHub Desktop.
Save aniltv06/6f3e9c6208e27a89259919eeb3c3d703 to your computer and use it in GitHub Desktop.
Find LCM and GCD, written in swift
/*
Returns the Greatest Common Divisor of two numbers.
*/
func gcd(_ x: Int, _ y: Int) -> Int {
var a = 0
var b = max(x, y)
var r = min(x, y)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
/*
Returns the least common multiple of two numbers.
*/
func lcm(_ x: Int, _ y: Int) -> Int {
return x / gcd(x, y) * y
}
lcm(10, 8) // 40
lcm(28,36) //252
lcm(36,45) //180
lcm(28,45) //1260
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment