Maximize the product of four factors of a Number | Java implementation of above approach ; Declare the ArrayList of factors for storing the ; function to find out the factors of a number ; Loop until the i reaches the sqrt ( n ) ; Check if i is a factor of n ; if both the factors are same we only push one factor ; factor1 is pushed ; factor2 is pushed ; Function to find the maximum product ; Initialize the product with - 1 ; Find the sum of factors and store it in s ; Compare whether it is equal to the n ; product of factors ; Check whether we have a better p now if yes update ; Driver Code ; initializes the List with the divisors of n ; prints out the maximised product .
import java . util . ArrayList ; import java . util . List ; public class GFG { static List < Integer > factors = new ArrayList < > ( 10 ) ; static void findFactors ( int n ) { for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( ( n / i ) == i ) { factors . add ( factors . size ( ) , i ) ; } else { factors . add ( factors . size ( ) , n / i ) ; factors . add ( factors . size ( ) , i ) ; } } } } static int findProduct ( int n ) { int product = - 1 ; int si = factors . size ( ) ; for ( int i = 0 ; i < si ; i ++ ) { for ( int j = 0 ; j < si ; j ++ ) { for ( int k = 0 ; k < si ; k ++ ) { for ( int l = 0 ; l < si ; l ++ ) { int s = factors . get ( i ) + factors . get ( j ) + factors . get ( k ) + factors . get ( l ) ; if ( s == n ) { int p = factors . get ( i ) * factors . get ( j ) * factors . get ( k ) * factors . get ( l ) ; if ( p > product ) { product = p ; } } } } } } return product ; } public static void main ( String [ ] args ) { int n = 10 ; findFactors ( n ) ; System . out . println ( findProduct ( n ) ) ; } }