# Maximize the product of four factors of a Number in C++

C++Server Side ProgrammingProgramming

Given the task is to calculate the maximum product that can be obtained from four factors A, B, C, D of a given number N, given the condition −

The sum of the four factors should be equal to the number N, that is, N=A+B+C+D.

Input − N=10

Output − 20

Explanation − The factors of 10 are: 1, 2, 5, 10.

Maximum product can be obtained by multiplying 5*2*2*1=20 and also it satisfies the given condition, that is, 5+2+2+1=10.

Input − N=16

Output − 256

Explanation − The factors of 16 are: 1, 2, 4, 8, 16.

Maximum product can be obtained by multiplying 4*4*4*4=256 and also it satisfies the given condition, that is, 4+4+4+4=16.

## Approach used in the below program as follows

• Create an array Factors[] of type int to store the factors of given number and a variable K=0 of type int to keep track of the size of array occupied .

• Create a function FindFactors() to find the factors of given numbers.

• Loop from i=1; i*i<=N; i++

• Inside the loop set if (N%i == 0) to check if I is a factor or not.

• If i is a factor, then check if (N/I == i). If yes then insert i into the Factors[] else pass both N/i and i into Factors[].

• Create function Product() to find the maximum product out of the factors.

• Initialize int product=0; and size=K+1;

• Initialize four new nested loops and run them till ‘size’.

• Inside the loops, initialize int sum= Factors[i] + Factors[] + Factors[k] + Factors[l];

• Check if (sum == N) and if so then initialize pro=Factors[i] * Factors[j] * Factors[k] * Factors[l];

• Then check if (pro > product), if so then put product=pro;

• return product

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//Array to store the factors
int Factors;
int K=0;
//Function to find out the factors
int FindFactors(int N){
//Looping until i reaches the sqrt(N)
for (int i = 1; i * i <= N; i++){
if (N % i == 0){
/* if both the factors are same then only one will be inserted*/
if ((N / i) == i){
Factors[K]=i;
K++;
}
else{
//Inserting 1st factor in array
Factors[K]=N/i;
K++;
//Inserting 2st factor in array
Factors[K]=i;
K++;
}
}
}
}
// Function to find the maximum product
int Product(int N){
int product = 0;
int size = K+1;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
for (int k = 0; k < size; k++)
for (int l = 0; l < size; l++){
int sum = Factors[i] + Factors[j] + Factors[k] + Factors[l];
//Checking if the sum is equal to N
if (sum == N){
//Multiplying the factors
int pro = Factors[i] * Factors[j] * Factors[k] * Factors[l];
//Replacing the value of product if a larger value is found
if(pro > product)
product = pro;
}
}
return product;
}
//Main function
int main(){
int N = 10;
//Calling function to find factors of N
FindFactors(N);
//Calling function to find the maximum product
cout<<Product(N);
return 0;
}

## Output

If we run the above code we will get the following output −

Maximum Profit: 20