picasothakkar
asked on
Finding the LCM of given n numbers.
Any one can write the code for finding the LCM of given n numbers.
I have written the code for finding the LCM of 2 numbers, but I need to find the LCM of given n numbers.
int gcd(int a, int b)
{
if (a==0 || b==0) return max(a,b);
if (a > b) return gcd(b, a);
if (!(b % a)) return a;
return gcd(a, b % a);
}
int lcm(int a, int b)
{
return b*a/gcd(a,b);
}
I have written the code for finding the LCM of 2 numbers, but I need to find the LCM of given n numbers.
int gcd(int a, int b)
{
if (a==0 || b==0) return max(a,b);
if (a > b) return gcd(b, a);
if (!(b % a)) return a;
return gcd(a, b % a);
}
int lcm(int a, int b)
{
return b*a/gcd(a,b);
}
p.s. this sounds suspiciously like homework, thus no code.
wouldn't it be
lcm(a1,...,aN) = lcm(a1,lcm(a2,...aN)) ???
lcm(a1,...,aN) = lcm(a1,lcm(a2,...aN)) ???
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If lcm_n is called with only one number, return that number.
If lcm_n is called with more than one number, then have it call itself recursively.
a = lcm_n of the first half of the numbers
b = lcm_n of the second half of the numbers
return lcm(a,b)