Find the winner of the game based on greater number of divisors | Java implementation of the above approach ; Function to return the count of divisors of elem ; Function to return the winner of the game ; Convert every element of A [ ] to their divisor count ; Convert every element of B [ ] to their divisor count ; Sort both the arrays ; For every element of A apply Binary Search to find number of pairs where A wins ; B wins if A doesnot win ; Driver code
import java . util . * ; class GFG { static int divisorcount ( int elem ) { int ans = 0 ; for ( int i = 1 ; i <= Math . sqrt ( elem ) ; i ++ ) { if ( elem % i == 0 ) { if ( i * i == elem ) ans ++ ; else ans += 2 ; } } return ans ; } static String findwinner ( int A [ ] , int B [ ] , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { A [ i ] = divisorcount ( A [ i ] ) ; } for ( int i = 0 ; i < M ; i ++ ) { B [ i ] = divisorcount ( B [ i ] ) ; } Arrays . sort ( A ) ; Arrays . sort ( B ) ; int winA = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int val = A [ i ] ; int start = 0 ; int end = M - 1 ; int index = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( B [ mid ] <= val ) { index = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } winA += ( index + 1 ) ; } int winB = N * M - winA ; if ( winA > winB ) { return " A " ; } else if ( winB > winA ) { return " B " ; } return " Draw " ; } public static void main ( String [ ] args ) { int A [ ] = { 4 , 12 , 24 } ; int N = A . length ; int B [ ] = { 25 , 28 , 13 , 45 } ; int M = B . length ; System . out . print ( findwinner ( A , B , N , M ) ) ; } }