C++中求数字的四个因子的最大乘积
给定任务是计算从给定数字 N 的四个因子 A、B、C、D 中获得的最大乘积,给定条件 -
四个因子的和应等于数字 N,即 N=A+B+C+D。
输入 - N=10
输出 - 20
解释 - 10 的因子为:1、2、5、10。
最大乘积可以通过乘以 5*2*2*1=20 获得,并且满足给定条件,即 5+2+2+1=10。
输入 - N=16
输出 - 256
解释 - 16 的因子为:1、2、4、8、16。
最大乘积可以通过乘以 4*4*4*4=256 获得,并且满足给定条件,即 4+4+4+4=16。
下面程序中使用的的方法如下
创建一个 int 类型的数组 Factors[] 来存储给定数字的因子,以及一个 int 类型的变量 K=0 来跟踪数组已占用的大小。
创建一个函数 FindFactors() 来查找给定数字的因子。
循环从 i=1; i*i<=N; i++
在循环内部设置 if (N%i == 0) 来检查 I 是否为因子。
如果 i 是一个因子,则检查 if (N/I == i)。如果是,则将 i 插入 Factors[],否则将 N/i 和 i 都传递到 Factors[] 中。
创建函数 Product() 以从因子中找到最大乘积。
初始化 int product=0; 和 size=K+1;
初始化四个新的嵌套循环并运行它们直到 'size'。
在循环内部,初始化 int sum= Factors[i] + Factors[] + Factors[k] + Factors[l];
检查 if (sum == N),如果为真,则初始化 pro=Factors[i] * Factors[j] * Factors[k] * Factors[l];
然后检查 if (pro > product),如果为真,则将 product=pro;
返回 product
示例
#include <bits/stdc++.h> using namespace std; //Array to store the factors int Factors[30]; 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++){ //Adding each set of factors 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; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果我们运行以上代码,我们将得到以下输出 -
Maximum Profit: 20