Number of co | Java program for the above approach ; Function to check whether given integers are co - prime or not ; Utility function to count number of co - prime pairs ; Traverse the array ; If co - prime ; Increment count ; Return count ; Function to count number of co - prime pairs ; Stores digits in string form ; Sort the list ; Keep two copies of list l ; Generate 2 digit numbers using d1 and d2 ; If current number does not exceed N ; Stores length of list ; Stores number of co - prime pairs ; Print number of co - prime pairs ; Driver Code ; Given value of N , d1 , d2 ; Function call to count number of co - prime pairs
import java . util . * ; class GFG { static int GCD ( int a , int b ) { return b == 0 ? a : GCD ( b , a % b ) ; } static boolean coprime ( int a , int b ) { if ( GCD ( a , b ) == 1 ) return true ; return false ; } static int numOfPairs ( ArrayList < String > arr , int N ) { int count = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( coprime ( Integer . parseInt ( arr . get ( i ) ) , Integer . parseInt ( arr . get ( j ) ) ) ) { count = count + 1 ; } } } return count ; } static void noOfCoPrimePairs ( int N , int d1 , int d2 ) { ArrayList < String > l = new ArrayList < String > ( ) ; l . add ( Integer . toString ( d1 ) ) ; l . add ( Integer . toString ( d2 ) ) ; Collections . sort ( l ) ; if ( N < Integer . parseInt ( l . get ( 1 ) ) ) return ; ArrayList < String > total = new ArrayList < String > ( l ) ; ArrayList < String > temp2 = new ArrayList < String > ( l ) ; int flag = 0 ; ArrayList < String > temp3 = new ArrayList < String > ( l ) ; while ( l . get ( 0 ) . length ( ) < 10 ) { for ( int i = 0 ; i < l . size ( ) ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { if ( Integer . parseInt ( l . get ( i ) + temp2 . get ( j ) ) > N ) { flag = 1 ; break ; } total . add ( l . get ( i ) + temp2 . get ( j ) ) ; temp3 . add ( l . get ( i ) + temp2 . get ( j ) ) ; } if ( flag == 1 ) break ; } if ( flag == 1 ) break ; l = temp3 ; temp3 . clear ( ) ; } int lenOfTotal = total . size ( ) ; int ans = numOfPairs ( total , lenOfTotal ) ; System . out . print ( ans ) ; } public static void main ( String args [ ] ) { int N = 30 , d1 = 2 , d2 = 3 ; noOfCoPrimePairs ( N , d1 , d2 ) ; } }