กำหนดให้งานคือการคำนวณผลิตภัณฑ์สูงสุดที่สามารถรับได้จากปัจจัยสี่ตัว A, B, C, D ของจำนวนที่กำหนด N ตามเงื่อนไข -
ผลรวมของปัจจัยทั้งสี่ควรเท่ากับจำนวน 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
แนวทางที่ใช้ในโปรแกรมด้านล่างดังนี้
-
สร้างอาร์เรย์ Factors[] ของประเภท int เพื่อเก็บปัจจัยของตัวเลขที่กำหนดและตัวแปร K=0 ของประเภท int เพื่อติดตามขนาดของอาร์เรย์ที่ใช้งาน
-
สร้างฟังก์ชัน FindFactors() เพื่อค้นหาตัวประกอบของตัวเลขที่กำหนด
-
วนจาก i=1; ผม*ผม<=N; ผม++
-
ภายใน loop set ถ้า (N%i ==0) ตรวจสอบว่า I เป็นปัจจัยหรือไม่
-
หาก i เป็นปัจจัย ให้ตรวจสอบว่า (N/I ==i) ถ้าใช่ ให้ใส่ i ลงใน Factors[] มิฉะนั้นจะผ่านทั้ง N/i และ i ไปยัง Factors[]
-
สร้างฟังก์ชัน Product() เพื่อค้นหาผลิตภัณฑ์สูงสุดจากปัจจัยต่างๆ
-
เริ่มต้นผลิตภัณฑ์ int=0; และ size=K+1;
-
เริ่มต้นลูปที่ซ้อนกันใหม่สี่ลูปและเรียกใช้จนถึง "ขนาด"
-
ภายในลูป เริ่มต้น int sum=Factors[i] + Factors[] + Factors[k] + Factors[l];
-
ตรวจสอบว่า (ผลรวม ==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