Skip to content

Instantly share code, notes, and snippets.

@kmark
Created November 16, 2014 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmark/df58004a206e8caac131 to your computer and use it in GitHub Desktop.
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.
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