Check if all the pairs of an array are coprime with each other | Java implementation of the above approach ; Function to store and check the factors ; Check if factors are equal ; Check if the factor is already present ; Insert the factor in set ; Check if the factor is already present ; Insert the factors in set ; Function to check if all the pairs of array elements are coprime with each other ; Check if factors of A [ i ] haven 't occurred previously ; Driver Code
import java . util . * ; class GFG { static boolean findFactor ( int value , HashSet < Integer > factors ) { factors . add ( value ) ; for ( int i = 2 ; i * i <= value ; i ++ ) { if ( value % i == 0 ) { if ( value / i == i ) { if ( factors . contains ( i ) ) { return true ; } else { factors . add ( i ) ; } } else { if ( factors . contains ( i ) || factors . contains ( value / i ) ) { return true ; } else { factors . add ( i ) ; factors . add ( value / i ) ; } } } } return false ; } static boolean allCoprime ( int A [ ] , int n ) { boolean all_coprime = true ; HashSet < Integer > factors = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] == 1 ) continue ; if ( findFactor ( A [ i ] , factors ) ) { all_coprime = false ; break ; } } return all_coprime ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 5 , 11 , 7 , 19 } ; int arr_size = A . length ; if ( allCoprime ( A , arr_size ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " No " ) ; } } }