Check whether the exchange is possible or not | Java implementation of the approach ; Recursive function to return gcd of a and b ; Function that returns true if the exchange is possible ; Find the GCD of the array elements ; If the exchange is possible ; Driver code
class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static boolean isPossible ( int [ ] arr , int n , int p ) { int gcd = 0 ; for ( int i = 0 ; i < n ; i ++ ) gcd = __gcd ( gcd , arr [ i ] ) ; if ( p % gcd == 0 ) return true ; return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 9 } ; int n = arr . length ; int p = 3 ; if ( isPossible ( arr , n , p ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }