LCM of given array elements
PROBLEM :
Given an array A[ ] of N numbers, your task is to find LCM of it.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow . The first line of each test case contains an integer N denoting the number of array elements. The next line contains N space separated values of array A[ ] .
Output:
For each test case in a new line print the lcm of the elements of the array .
Constraints:
1<=T<=100
1<=N<=20
1<=A[ ] <=20
Example:
Input
1
4
1 2 8 3
Output
24
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int FindLCM(int [],int ) ;
int findGCD(int ,int ) ;
int main()
{
int t,no,a[20],i,lcm ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>a[i] ;
lcm=FindLCM(a,no) ;
cout<<lcm<<endl ;
}
return 0;
}
int FindLCM(int a[],int no)
{
int i ,ans ;
ans=a[0] ;
for(i=1;i<no;i++)
{
ans=((ans*a[i])/(ans>a[i]?findGCD(a[i],ans):findGCD(ans,a[i]))) ;
}
return ans ;
}
int findGCD(int n1,int n2)
{
int rem ;
rem=n2%n1 ;
if(rem==0)
return n1 ;
else
findGCD(rem,n1) ;
}
---------------------------------------------------------------------------------
Given an array A[ ] of N numbers, your task is to find LCM of it.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow . The first line of each test case contains an integer N denoting the number of array elements. The next line contains N space separated values of array A[ ] .
Output:
For each test case in a new line print the lcm of the elements of the array .
Constraints:
1<=T<=100
1<=N<=20
1<=A[ ] <=20
Example:
Input
1
4
1 2 8 3
Output
24
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int FindLCM(int [],int ) ;
int findGCD(int ,int ) ;
int main()
{
int t,no,a[20],i,lcm ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>a[i] ;
lcm=FindLCM(a,no) ;
cout<<lcm<<endl ;
}
return 0;
}
int FindLCM(int a[],int no)
{
int i ,ans ;
ans=a[0] ;
for(i=1;i<no;i++)
{
ans=((ans*a[i])/(ans>a[i]?findGCD(a[i],ans):findGCD(ans,a[i]))) ;
}
return ans ;
}
int findGCD(int n1,int n2)
{
int rem ;
rem=n2%n1 ;
if(rem==0)
return n1 ;
else
findGCD(rem,n1) ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment