LCM
Uses the Euclidean Algorithm to determine the Least Common Multiplier for an array of integers
Source
public static class LeastCommonMultiplierCalc {
/// <summary>
/// Uses the Euclidean Algorithm to determine the Least Common Multiplier for an array of integers
/// </summary>
/// <param name="values">Array of int values</param>
/// <returns>The Lease Common Multiplier for values provided</returns>
public static int LCM(this int[] values) {
var retval = values[0];
for (var i = 1; i < values.Length; i++) {
retval = GCD(retval, values[i]);
}
return retval;
}
private static int GCD(int val1, int val2) {
while (val1 != 0 && val2 != 0) {
if (val1 > val2)
val1 %= val2;
else
val2 %= val1;
}
return Math.Max(val1, val2);
}
}
Example
var numbers = new[] { 21, 63, 91, 119, 154 };
Console.WriteLine(numbers.LCM());
var veryLargeNumbers = new [] {596523235,835132529,477218588,2147483646,2028178999,1073741823};
Console.WriteLine(veryLargeNumbers.LCM());