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

C++Server Side ProgrammingProgramming

Suppose we have an integer N. The task is to find all factors of N and display the product of four factors of N, such that −

  • Sum of their four factors are equal to N

  • The product of four factors is maximum

Suppose the number is 24, then the product is 1296. As we know all of the factors are 1, 2, 3, 4, 6, 8, 12, 24. We have to choose the factors 6 four times. So 6 + 6 + 6 + 6 = 24. Here the product is maximum.

To solve this, we have to find all factors from 1 to N, then we have to check these conditions

  • If the N is prime, then the answer will be false

  • If the given n is divisible by 4, then the answer will be x^4. Where x is a quotient when n is divisible by 4.

  • If it is possible to find the answer then, the answer must include the third last factor two times. Then run the nested loop for the other two factors.

Example

 Live Demo

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool isPrime(int n) {
   if (n <= 1)
      return false;
   if (n <= 3)
      return true;
   if (n % 2 == 0 || n % 3 == 0)
      return false;
   for (int i = 5; i * i <= n; i = i + 6)
      if (n % i == 0 || n % (i + 2) == 0)
   return false;
   return true;
}
void get_factors(int N, vector<int> fact_vectors[]) {
   for (int i = 2; i < N; i++) {
      for (int j = 1; j * j <= i; j++) {
         if (i % j == 0) {
            if (i / j == j)
            fact_vectors[i].push_back(j);
            else {
               fact_vectors[i].push_back(j);
               fact_vectors[i].push_back(i / j);
            }
         }
      }
      sort(fact_vectors[i].begin(), fact_vectors[i].end());
   }
}
int getProduct(int n) {
   vector<int> v[n + 100];
   get_factors(n + 100, v);
   if (n % 4 == 0) {
      int x = n / 4;
      x *= x;
      return x * x;
   } else {
      if (isPrime[n])
      return -1;
      else {
         int ans = -1;
            if (v[n].size() > 2) {
               int fac = v[n][v[n].size() - 3];
               for (int i = v[n].size() - 1; i >= 0; i--) {
                  for (int j = v[n].size() - 1; j >= 0; j--) {
                     if ((fac * 2) + (v[n][j] + v[n][i]) == n)
                     ans = max(ans, fac * fac * v[n][j] * v[n][i]);
                  }
               }
            return ans;
         }
      }
   }
}
int main() {
   int n = 24;
   cout << "The product is: " << getProduct(n);
}

Output

The product is: 1296
raja
Published on 03-Jan-2020 10:04:07
Advertisements