Find four factors of N with maximum product and sum equal to N | Set | C ++ 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 [ i ] + v [ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findfactors ( int n ) { unordered_map < int , int > mpp ; vector < int > v , v1 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { v . push_back ( i ) ; if ( i != ( n / i ) && i != 1 ) v . push_back ( n / i ) ; } } int s = v . size ( ) ; int maxi = -1 ; pair < int , int > mp1 [ n + 5 ] ; for ( int i = 0 ; i < s ; i ++ ) { for ( int j = i ; j < s ; j ++ ) { if ( v [ i ] + v [ j ] < n ) { v1 . push_back ( v [ i ] + v [ j ] ) ; mp1 [ v [ i ] + v [ j ] ] = { v [ i ] , v [ j ] } ; mpp [ v [ i ] + v [ j ] ] = 1 ; } } } s = v1 . size ( ) ; for ( int i = 0 ; i < s ; i ++ ) { int el = n - ( v1 [ i ] ) ; if ( mpp [ el ] == 1 ) { int a = mp1 [ v1 [ i ] ] . first ; int b = mp1 [ v1 [ i ] ] . second ; int c = mp1 [ n - v1 [ i ] ] . first ; int d = mp1 [ n - v1 [ i ] ] . second ; maxi = max ( a * b * c * d , maxi ) ; } } if ( maxi == -1 ) cout << " Not ▁ Possible STRNEWLINE " ; else { cout << " The ▁ maximum ▁ product ▁ is ▁ " << maxi << endl ; } } int main ( ) { int n = 50 ; findfactors ( n ) ; return 0 ; }