Skip to content

Instantly share code, notes, and snippets.

@mikesigs
Last active April 22, 2016 19:37
Show Gist options
  • Save mikesigs/6bb5c5e3f893ba90d50598963d86dc33 to your computer and use it in GitHub Desktop.
Save mikesigs/6bb5c5e3f893ba90d50598963d86dc33 to your computer and use it in GitHub Desktop.
Lowest Common Denominator
void Main()
{
var input = new long[,] { {1, 2}, {1, 3}, {1, 4} };
var fractions =
from i in Enumerable.Range(0, input.GetUpperBound(0) + 1)
select Tuple.Create(input[i,0], input[i,1]);
var denoms = fractions.Select(t => t.Item2).ToArray();
var lcd = LCM(denoms);
var normalizedFractions =
from f in fractions
select Tuple.Create(f.Item1 * (lcd/f.Item2), lcd);
var result = String.Join("", normalizedFractions.Select(f => $"({f.Item1},{f.Item2})"));
result.Dump(); // For LinqPad output
}
/// Get the factors of specificed long
public IEnumerable<long> FactorsOf(long num)
{
return
from i in Enumerable.Range(1, (int)num)
where num % i == 0
select (long)i;
}
/// Greatest Common Devisor of two longs
public long GCD(long num1, long num2)
{
return FactorsOf(num1).Intersect(FactorsOf(num2)).Max();
}
/// Least Common Multiple of two longs
public long LCM(long num1, long num2)
{
return (num1 * num2) / GCD(num1, num2);
}
/// Least Common Multiple of a range of numbers
public long LCM(long[] nums)
{
if (nums.Length == 1) { return nums[0]; }
return nums.Aggregate(
LCM(nums[0], nums[1]),
(acc, n) => LCM(acc, n));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment