Maximize the product of four factors of a Number | C ++ implementation of above approach ; Declare the vector 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 vectors with the divisors of n ; prints out the maximised product .
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > factors ; void findFactors ( int n ) { for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( ( n / i ) == i ) factors . push_back ( i ) ; else { factors . push_back ( n / i ) ; factors . push_back ( i ) ; } } } } 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 [ i ] + factors [ j ] + factors [ k ] + factors [ l ] ; if ( s == n ) { int p = factors [ i ] * factors [ j ] * factors [ k ] * factors [ l ] ; if ( p > product ) product = p ; } } return product ; } int main ( ) { int n = 10 ; findFactors ( n ) ; cout << findProduct ( n ) ; return 0 ; }