Skip to content

Instantly share code, notes, and snippets.

@banderson
Created February 6, 2012 16:03
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 banderson/1752892 to your computer and use it in GitHub Desktop.
Save banderson/1752892 to your computer and use it in GitHub Desktop.
Math Helpers: Greatest Common Divisor & Least Common Multiple
public class MathHelper {
// Find the Greatest Common Divisor using Euclid's Algorithm
// Adapted from: http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm
public static int GreatestCommonDivisor(int a, int b) {
// base case: when b is zero, we've found the GCD
if (b == 0) {
return a;
}
// recurse until we find base case
return GreatestCommonDivisor(b, a % b);
}
// Least Common Multiple, based on the GCD calculation above
// Adapted from: http://en.wikipedia.org/wiki/Least_common_multiple#Reduction_by_the_greatest_common_divisor
public static int LeastCommonMultiple(int a, int b) {
return (Math.abs(a * b)) / GreatestCommonDivisor(a, b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment