C++での数値の4つの因数の積を最大化する
タスクが与えられた場合、条件-
が与えられた場合、与えられた数Nの4つの因子A、B、C、Dから得られる最大積を計算することです。4つの要素の合計は、数値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が因子である場合は、(N / I ==i)かどうかを確認します。はいの場合はiをFactors[]に挿入し、そうでない場合はN/iとiの両方をFactors[]に渡します。
-
関数Product()を作成して、因子から最大の積を見つけます。
-
int product=0を初期化します。およびsize=K + 1;
-
4つの新しいネストされたループを初期化し、「サイズ」になるまで実行します。
-
ループ内で、int sum =Factors [i] + Factors [] + Factors [k] + Factors [l];
を初期化します。 -
(sum ==N)かどうかを確認し、そうであれば、pro =Factors [i] * Factors [j] * Factors [k] * Factors [l];
を初期化します。 -
次に、(pro> product)かどうかを確認し、そうであれば、product =pro;
を入力します。 -
返品
例
#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;
} 出力
上記のコードを実行すると、次の出力が得られます-
Maximum Profit: 20
-
C ++でサブ配列を反転して、0の数を最大化します
問題の説明 バイナリ配列が与えられた場合、サブ配列の1回の反転が許可されている配列内のゼロの最大数を見つけます。フリップ操作は、すべての0を1に、1を0に切り替えます arr1 ={1、1、0、0、0、0、0}の場合 最初の21を0に反転すると、次のようにサイズ7のサブ配列を取得できます- {0, 0, 0, 0, 0, 0, 0} アルゴリズム 1. Consider all subarrays and find a subarray with maximum value of (count of 1s) – (count of 0s) 2. Considers this
-
C++での最大積4倍の数を見つける
n個の要素を持つ1つの整数配列があるとします。配列内の4倍の最大積を見つける必要があります。したがって、配列が[3、5、20、6、10]のような場合、最終積は6000であり、4倍の要素は10、5、6、20です。 これを解決するには、次の手順に従います- 配列を昇順で並べ替えます xが最後の4つの要素の積、yが最初の4つの要素の積、zが最初の2つと次の2つの要素の積であると仮定します x、y、zの最大値を返します。 例 #include<iostream> #include<algorithm> using namespace std; int maxQuadP