Find element in array that divides all array elements | CPP program to find such number in the array that all array elements are divisible by it ; Returns gcd of two numbers . ; Function to return the desired number if exists ; Find GCD of array ; Check if GCD is present in array ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int findNumber ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) ans = gcd ( ans , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == ans ) return ans ; return -1 ; } int main ( ) { int arr [ ] = { 2 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findNumber ( arr , n ) << endl ; return 0 ; }