I want to find out Least Common Multiple(LCM) of more than two numbers. I know the formula of lcm(a,b) = (a * b) / gcd(a,b). Let's say, I have an array of numbers: [2, 6, 8, 13] and the the lcm should be modulo M = 1000000007.
I have seen below code to calculate the LCM of multiple numbers but I am not understanding how the calculation is going on with both the loops.
int arr[] = {2, 6, 8, 13}, n = 4
long long int ans=1;
long long int M=1000000007;
for(int i=0;i<n;i++) // Calculating LCM
{
for(int j=i+1;j<n;j++)
{
arr[j]=arr[j]/__gcd(arr[i],arr[j]);
}
ans=((ans%M)*(arr[i]%M))%M;
}
return (ans)%M;
Can anyone please help me to understand the LCM calculation in the above code?
Knowing that
gcd(a, b)represents the product of all the prime factors shared byaandb, what is the significance ofa / gcd(a,b)?a / gcd(a, b)is equal to the prime factors ofathat are not inb.Therefore, when you multiple that quantity by
b, you get a product of all the prime factors ofband all the prime factors ofathat are not inb. This is preciselylcm(a, b).Let's extend that to an arbitrary number of integers.
The
lcm(a, b)isatimes all the prime factors ofbnot inaor:Easy enough, you knew that already.
But if we have a third number,
lcm(a, b, c)isatimes all the prime factors ofbnot inatimes all the prime factors ofcin neitheranorb. Well, the first part is straight forward, it's the same as above:How to calculate
all the prime factors of c in neither a nor bmight not be obvious at first, but it's not overly complicated:Which means that
And now, you can generalize easily:
But a more relevant formulation is the recursive version:
Or:
Here's an attempt at translating your code snippet to psuedocode
Compare this to the last definition of
lcmon an array, I tried to make them appear similar.Hopefully, that wasn't too confusing; I admit it may not be much of an explanation, but it is a starting point. Please let me know if anything is still unclear.