Find four factors of N with maximum product and sum equal to N

Write a program in C++ to find four factors of N with maximum product and sum equal to N:

#include <bits/stdc++.h>

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 Possiblen";

    else {

        cout << "The maximum product is " << maxi << endl;
    }
}

int main()
{
    int n = 50;

    findfactors(n);

    return 0;

}

 

Leave a Comment