Find four factors of N with maximum product and sum equal to N | Set 3 | Java implementation of above approach ; Function to find primes ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to find factors ; run a loop upto square root of that number ; if the n is perfect square ; otherwise push it 's two divisors ; sort the divisors ; Function to find max product ; To store factors of ' n ' ; find factors ; if it is divisible by 4. ; if it is prime ; otherwise answer will be possible ; include last third factor ; nested loop to find other two factors ; Driver code ; function call
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static Vector < Vector < Integer > > v = new Vector < Vector < Integer > > ( ) ; static void factors ( int N ) { for ( int i = 2 ; i < N ; i ++ ) { for ( int j = 1 ; j * j <= i ; j ++ ) { if ( i % j == 0 ) { if ( i / j == j ) v . get ( i ) . add ( j ) ; else { v . get ( i ) . add ( j ) ; v . get ( i ) . add ( i / j ) ; } } } Collections . sort ( v . get ( i ) ) ; } } static int product ( int n ) { v . clear ( ) ; for ( int i = 0 ; i < n + 100 ; i ++ ) v . add ( new Vector < Integer > ( ) ) ; factors ( n + 100 ) ; if ( n % 4 == 0 ) { int x = n / 4 ; x *= x ; return x * x ; } else { if ( isPrime ( n ) ) return - 1 ; else { int ans = - 1 ; if ( v . get ( n ) . size ( ) > 2 ) { int fac = v . get ( n ) . get ( v . get ( n ) . size ( ) - 3 ) ; for ( int i = v . get ( n ) . size ( ) - 1 ; i >= 0 ; i -- ) { for ( int j = v . get ( n ) . size ( ) - 1 ; j >= 0 ; j -- ) { if ( ( fac * 2 ) + ( v . get ( n ) . get ( j ) + v . get ( n ) . get ( i ) ) == n ) ans = Math . max ( ans , fac * fac * v . get ( n ) . get ( j ) * v . get ( n ) . get ( i ) ) ; } } return ans ; } } } return 0 ; } public static void main ( String args [ ] ) { int n = 24 ; System . out . println ( product ( n ) ) ; } }