06/04/2017

Geeksforgeeks Solution For " GCD of Array "

GeeksforGeeks Solution For Hard Domain .Below You Can Find The Solution Of  School Basic ,Easy ,Medium . Or Hackerrank Solution You Can Also Direct Submit Your Solution to Geeksforgeeks Same Problem .You Need to login then you can submit you answers 

Problem :- GCD of Array

Submit Your Solution :- Click Here 

Solution :- 

Method 1:-

#include<bits/stdc++.h>
#define LL long long int
#define mod 1000000007
using namespace std;
LL gcd(LL a, LL b) 
{
    if (a == 0) return b;
    if (b == 0) return a;
    if (a < 0) return gcd(-1 * a, b);
    if (b < 0) return gcd(a, -1 * b);
    if (a > b) return gcd(b, a);
    return gcd(b%a, a);
}

LL arr[1000005];

int main()
{
   LL t,n,i,lcm_new;
   cin>>t;
   while(t--)
   {
    cin>>n;
    for(i=0;i<n;i++)
    cin>>arr[i];
    LL hcf=arr[0];
    for(i=1;i<n;i++)
    {
    hcf=gcd(hcf,arr[i]);
    }
    cout<<hcf<<endl;
   }
}

Method 2:-

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


Output:-



Geeksforgeeks Solution For " GCD of Array "

Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: