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

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )