C++ 查找N的四个因数,使其乘积最大且和等于N。


概念

对于给定的整数N,我们的任务是确定N的所有因数,并打印N的四个因数的乘积,使得 -

  • 四个因数的和等于N。
  • 四个因数的乘积最大。

如果无法找到4个这样的因数,则打印“不可能”。

需要注意的是,所有四个因数可以彼此相等以最大化乘积。

输入

24

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

All the factors are -> 1 2 4 5 8 10 16 20 40 80
Product is -> 160000

选择因数20四次,

因此,20+20+20+20 = 24 且乘积最大。

方法

以下是解决此问题的逐步算法 -

  • 首先通过从1访问到N的平方根来确定数字“N”的因数,并验证“i”和“n/i”是否能整除N,并将它们存储在向量中。
  • 现在我们对向量进行排序并打印每个元素。
  • 确定三个数字以使用第四个数字最大化乘积,实现三个循环。
  • 最后,我们用先前的乘积替换下一个最大乘积。
  • 找到四个因数时打印乘积。

示例

 实时演示

// C++ program to find four factors of N
// with maximum product and sum equal to N
#include <bits/stdc++.h>
using namespace std;
// Shows function to find factors
// and to print those four factors
void findfactors2(int n1){
   vector<int> vec2;
   // Now inserting all the factors in a vector s
   for (int i = 1; i * i <= n1; i++) {
      if (n1 % i == 0) {
         vec2.push_back(i);
         vec2.push_back(n1 / i);
      }
   }
   // Used to sort the vector
   sort(vec2.begin(), vec2.end());
   // Used to print all the factors
   cout << "All the factors are -> ";
   for (int i = 0; i < vec2.size(); i++)
      cout << vec2[i] << " ";
      cout << endl;
      // Now any elements is divisible by 1
      int maxProduct2 = 1;
      bool flag2 = 1;
      // implementing three loop we'll find
      // the three maximum factors
      for (int i = 0; i < vec2.size(); i++) {
         for (int j = i; j < vec2.size(); j++) {
            for (int k = j; k < vec2.size(); k++) {
               // Now storing the fourth factor in y
               int y = n1 - vec2[i] - vec2[j] - vec2[k];
            // It has been seen that if the fouth factor become negative
            // then break
            if (y <= 0)
               break;
            // Now we will replace more optimum number
            // than the previous one
            if (n1 % y == 0) {
               flag2 = 0;
               maxProduct2 = max(vec2[i] * vec2[j] * vec2[k] *y,maxProduct2);
            }
         }
      }
   }
   // Used to print the product if the numbers exist
   if (flag2 == 0)
     cout << "Product is -> " << maxProduct2 << endl;
   else
      cout << "Not possible" << endl;
}
// Driver code
int main(){
   int n1;
   n1 = 80;
   findfactors2(n1);
   return 0;
}

输出

All the factors are -> 1 2 4 5 8 10 16 20 40 80
Product is -> 160000

更新于: 2020年7月24日

77 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告