Tuesday, 16 September 2014

LCM of n numbers




LCM of n numbers


Input  :
First line contains the number of numbers that are input  'n', where n>1
Next line contains 'n' positive integers whose LCM is to be calculated.

Output  :
One line containing the LCM of the 'n' numbers

#include <stdio.h>
int gcd(int a,int b){
   int g ;
  while (b!=0){
   g=a%b;
   a=b;
   b=g;}

return a; // a is the gcd
}

int main(){
    int lcm , n , num1,num,i;
    scanf("%d",&n);
    scanf("%d",&num1);
     for (i=2;i<=n;i++){   
        scanf("%d",&num);
        lcm=(num1*num)/gcd(num1,num);
        num1=lcm;}


    printf("%d",num1);
    return 0;
    
    }

No comments:

Post a Comment