Find four factors of N with maximum product and sum equal to N | Set 3 | 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
function isPrime ( n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( let i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } function factors ( N , v ) { for ( let i = 2 ; i < N ; i ++ ) { for ( let j = 1 ; j * j <= i ; j ++ ) { if ( i % j == 0 ) { if ( i / j == j ) v [ i ] . push ( j ) ; else { v [ i ] . push ( j ) ; v [ i ] . push ( i / j ) ; } } } v . sort ( ( a , b ) => a - b ) ; } } function product ( n ) { let v = new Array ( ) ; for ( let i = 0 ; i < n + 100 ; i ++ ) { v . push ( new Array ( ) ) } factors ( n + 100 , v ) ; if ( n % 4 == 0 ) { let x = n / 4 ; x *= x ; return x * x ; } else { if ( isPrime [ n ] ) return - 1 ; else { let ans = - 1 ; if ( v [ n ] . length > 2 ) { let fac = v [ n ] [ v [ n ] . length - 3 ] ; for ( let i = v [ n ] . length - 1 ; i >= 0 ; i -- ) { for ( let j = v [ n ] . length - 1 ; j >= 0 ; j -- ) { if ( ( fac * 2 ) + ( v [ n ] [ j ] + v [ n ] [ i ] ) == n ) ans = Math . max ( ans , fac * fac * v [ n ] [ j ] * v [ n ] [ i ] ) ; } } return ans ; } } } } let n = 24 ; document . write ( product ( n ) ) ;