Find four factors of N with maximum product and sum equal to N | Set | Java program to find four factors of N with maximum product and sum equal to N ; Function to find factors and to print those four factors ; push all the factors in the container ; number of factors ; Initial maximum ; hash - array to mark the pairs ; form all the pair sums ; if the pair sum is less than n ; push in another container ; mark the sum with the elements formed ; mark in the map that v . get ( i ) + v . get ( j ) is present ; new size of all the pair sums ; iterate for all pair sum ; the required part ; if the required part is also present in pair sum ; find the elements with which the first pair is formed ; find the elements with which the second pair is formed ; check for previous maximum ; Driver code
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void findfactors ( int n ) { HashMap < Integer , Integer > mpp = new HashMap < > ( ) ; Vector < Integer > v = new Vector < Integer > ( ) , v1 = new Vector < Integer > ( ) ; for ( int i = 1 ; i <= ( int ) Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { v . add ( i ) ; if ( i != ( n / i ) && i != 1 ) v . add ( n / i ) ; } } int s = v . size ( ) ; int maxi = - 1 ; int mp1_first [ ] = new int [ n + 5 ] , mp1_second [ ] = new int [ n + 5 ] ; for ( int i = 0 ; i < s ; i ++ ) { for ( int j = i ; j < s ; j ++ ) { if ( v . get ( i ) + v . get ( j ) < n ) { v1 . add ( v . get ( i ) + v . get ( j ) ) ; mp1_first [ v . get ( i ) + v . get ( j ) ] = v . get ( i ) ; mp1_second [ v . get ( i ) + v . get ( j ) ] = v . get ( j ) ; mpp . put ( v . get ( i ) + v . get ( j ) , 1 ) ; } } } s = v1 . size ( ) ; for ( int i = 0 ; i < s ; i ++ ) { int el = n - ( v1 . get ( i ) ) ; if ( mpp . get ( el ) != null ) { int a = mp1_first [ v1 . get ( i ) ] ; int b = mp1_second [ v1 . get ( i ) ] ; int c = mp1_first [ n - v1 . get ( i ) ] ; int d = mp1_second [ n - v1 . get ( i ) ] ; maxi = Math . max ( a * b * c * d , maxi ) ; } } if ( maxi == - 1 ) System . out . println ( " Not ▁ Possible " ) ; else { System . out . println ( " The ▁ maximum ▁ product " + " ▁ is ▁ " + maxi ) ; } } public static void main ( String args [ ] ) { int n = 50 ; findfactors ( n ) ; } }