Find four factors of N with maximum product and sum equal to N | Set | 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
function findfactors ( n ) { let mpp = new Map ( ) ; let v = [ ] ; let v1 = [ ] ; for ( let i = 1 ; i <= Math . floor ( Math . sqrt ( n ) ) ; i ++ ) { if ( n % i == 0 ) { v . push ( i ) ; if ( i != Math . floor ( n / i ) && i != 1 ) v . push ( Math . floor ( n / i ) ) ; } } let s = v . length ; let maxi = - 1 ; let mp1_first = new Array ( n + 5 ) , mp1_second = new Array ( n + 5 ) ; for ( let i = 0 ; i < s ; i ++ ) { for ( let j = i ; j < s ; j ++ ) { if ( v [ i ] + v [ j ] < n ) { v1 . push ( v [ i ] + v [ j ] ) ; mp1_first [ v [ i ] + v [ j ] ] = v [ i ] ; mp1_second [ v [ i ] + v [ j ] ] = v [ j ] ; mpp . set ( v [ i ] + v [ j ] , 1 ) ; } } } s = v1 . length ; for ( let i = 0 ; i < s ; i ++ ) { let el = n - ( v1 [ i ] ) ; if ( mpp . get ( el ) != null ) { let a = mp1_first [ v1 [ i ] ] ; let b = mp1_second [ v1 [ i ] ] ; let c = mp1_first [ n - v1 [ i ] ] ; let d = mp1_second [ n - v1 [ i ] ] ; maxi = Math . max ( a * b * c * d , maxi ) ; } } if ( maxi == - 1 ) document . write ( " " ) ; else { document . write ( " " + " " + maxi ) ; } } let n = 50 ; findfactors ( n ) ;