Created
August 22, 2018 05:53
-
-
Save aniltv06/6f3e9c6208e27a89259919eeb3c3d703 to your computer and use it in GitHub Desktop.
Find LCM and GCD, written in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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