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;
}

輸出

如果我們執行以上程式碼,我們將得到以下輸出 -

Maximum Profit: 20

更新於: 2020-08-14

178 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.