GCD of Array
PROBLEM :
For a given array find out the GCD of the array.
Input:
First line of input contains the number of test cases 'T'. First line of test case contain an the size 'N' of array. Second line of test cases contain the array elements.
Output:
Find GCD and print it in seperate line.
Constraints:
1 <= T <= 32
1 <= N <= 20
1 <= Arr[i] <= 100
Example:
Input:
1
2
5 10
Output:
5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int GCD_of_Array(int [],int ) ;
int findGCD(int ,int ) ;
int main()
{
int t,arr[20],i,no ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>arr[i] ;
no=GCD_of_Array(arr,no) ;
cout<<no<<endl ;
}
return 0;
}
int GCD_of_Array(int arr[],int no)
{
int i,n ;
n=arr[0] ;
for(i=1;i<no;i++)
{
n=n>arr[i]?findGCD(n,arr[i]):findGCD(arr[i],n) ;
}
return n ;
}
int findGCD(int no1,int no2)
{
int rem ;
rem=no2%no1 ;
if(rem==0)
return no1 ;
else
return findGCD(rem,no1) ;
}
---------------------------------------------------------------------------------
For a given array find out the GCD of the array.
Input:
First line of input contains the number of test cases 'T'. First line of test case contain an the size 'N' of array. Second line of test cases contain the array elements.
Output:
Find GCD and print it in seperate line.
Constraints:
1 <= T <= 32
1 <= N <= 20
1 <= Arr[i] <= 100
Example:
Input:
1
2
5 10
Output:
5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int GCD_of_Array(int [],int ) ;
int findGCD(int ,int ) ;
int main()
{
int t,arr[20],i,no ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>arr[i] ;
no=GCD_of_Array(arr,no) ;
cout<<no<<endl ;
}
return 0;
}
int GCD_of_Array(int arr[],int no)
{
int i,n ;
n=arr[0] ;
for(i=1;i<no;i++)
{
n=n>arr[i]?findGCD(n,arr[i]):findGCD(arr[i],n) ;
}
return n ;
}
int findGCD(int no1,int no2)
{
int rem ;
rem=no2%no1 ;
if(rem==0)
return no1 ;
else
return findGCD(rem,no1) ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment