How do you calculate the least common multiple of multiple numbers?
So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.
So far this is how I did it
LCM = num1 * num2 / gcd ( num1 , num2 )
With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm
But I can't figure out how to calculate it for 3 or more numbers.
I just figured this out in Haskell:
I even took the time to write my own
gcd
function, only to find it in Prelude! Lots of learning for me today :DGCD needs a little correction for negative numbers:
int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } int lcm(int[] a, int n) { int res = 1, i; for (i = 0; i < n; i++) { res = res*a[i]/gcd(res, a[i]); } return res; }
Just for fun, a shell (almost any shell) implementation:
try it with:
to get
The biggest input and result should be less than
(2^63)-1
or the shell math will wrap.Using LINQ you could write:
Should add
using System.Linq;
and don't forget to handle the exceptions ...Here it is in Swift.