Created
February 6, 2012 16:03
-
-
Save banderson/1752892 to your computer and use it in GitHub Desktop.
Math Helpers: Greatest Common Divisor & Least Common Multiple
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
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