Find A and B from list of divisors | Java implementation of the approach ; Function to print A and B all of whose divisors are present in the given array ; Sort the array ; A is the largest element from the array ; Iterate from the second largest element ; If current element is not a divisor of A then it must be B ; If current element occurs more than once ; Print A and B ; Driver code
import java . util . * ; class GfG { static void printNumbers ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int A = arr [ n - 1 ] , B = - 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( A % arr [ i ] != 0 ) { B = arr [ i ] ; break ; } if ( i - 1 >= 0 && arr [ i ] == arr [ i - 1 ] ) { B = arr [ i ] ; break ; } } System . out . print ( " A ▁ = ▁ " + A + " , ▁ B ▁ = ▁ " + B ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 8 , 16 , 1 , 2 , 4 } ; int n = arr . length ; printNumbers ( arr , n ) ; } }