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.
You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.
I would go with this one (C#):
Just some clarifications, because at first glance it doesn't seams so clear what this code is doing:
Aggregate is a Linq Extension method, so you cant forget to add using System.Linq to your references.
Aggregate gets an accumulating function so we can make use of the property lcm(a,b,c) = lcm(a,lcm(b,c)) over an IEnumerable. More on Aggregate
GCD calculation makes use of the Euclidean algorithm.
lcm calculation uses Abs(a*b)/gcd(a,b) , refer to Reduction by the greatest common divisor.
Hope this helps,
Here is a Python one-liner (not counting imports) to return the LCM of the integers from 1 to 20 inclusive:
Python 3.5+ imports:
Python 2.7 imports:
Common logic:
In both Python 2 and Python 3, operator precedence rules dictate that the
*
and//
operators have the same precedence, and so they apply from left to right. As such,x*y//z
means(x*y)//z
and notx*(y//z)
. The two typically produce different results. This wouldn't have mattered as much for float division but it does for floor division.In R, we can use the functions mGCD(x) and mLCM(x) from the package numbers, to compute the greatest common divisor and least common multiple for all numbers in the integer vector x together:
And the Scala version: