Created
November 16, 2014 20:49
-
-
Save kmark/df58004a206e8caac131 to your computer and use it in GitHub Desktop.
Least common multiple calculator via greatest common denominator using Euclid's method. Includes both iterative and recursive implementations.
This file contains hidden or 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
int gcdIterative(int a, int b) { | |
while(true) { | |
if(a > b) { | |
a -= b; | |
continue; | |
} | |
if(b > a) { | |
b -= a; | |
continue; | |
} | |
// if a == b | |
return a; | |
} | |
} | |
int gcdRecursive(int a, int b) { | |
if(a > b) { | |
return gcdRecursive(a - b, b); | |
} | |
if(b > a) { | |
return gcdRecursive(a, b - a); | |
} | |
// if a == b | |
return a; | |
} | |
// LCM (a, b) = a / GCD(a, b) * b | |
int lcm(int a, int b) { | |
return a / gcdIterative(a, b) * b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment