4/06/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 "

Ghanendra Yadav

Ghanendra Yadav

Hello, I Am Ghanendra Yadav Owner of This Blog, I am professional Blogger and Programmer. I Love Programming, Logo Making, And Banner Designing. My Highest Qualification is MCA From NIT Warangal. You Can Find Me On Social Media Through Below Link And If You Have Any Query Related To Programming And Other Subject Comment Below or You Can Mail Me I Will Try To Answer Within 24 Hours Email:- yghanendra@student.nitw.ac.in

Find me on Social Media

Facebook | Twitter | Google+ | RSS Feed

No comments:

Post a Comment