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);

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Just create a lcm_n function that recursively calls itself or delegates to lcm.

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)
p.s. this sounds suspiciously like homework, thus no code.
wouldn't it be

lcm(a1,...,aN) = lcm(a1,lcm(a2,...aN)) ???
I think you can optimize GCDs code to be like:
//assume that a and b cannot both be 0
int GCD(int a, int b)
   if (b==0) return a;
   return GCD(b,a%b);
>>but I need to find the LCM of given n numbers
so, the numbers should be stored in array, right?
then you can do it using for loop :
int array[N];
int output = array[0];    
for(int i = 1; i<N; i++)
     output = lcm(output,array[i]);
or you can do it recursively as  experts said ..

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.