在Java中最大化所有人員X的總利潤
我們有5個整數變數Num、P1、P2、profit_P1和profit_P2,任務是在[1,Num]範圍內所有自然數中最大化利潤。方法是:如果一個正數能被P1整除,利潤增加profit_P1;如果該數能被P2整除,利潤增加profit_P2。此外,一個正整數的利潤最多隻能加一次。
讓我們用例子來理解:
輸入− int num = 4, P1 = 6, P2 = 2, profit_P1 = 8, profit_P2 = 2;
輸出− 最大化所有人員X的總利潤 4
解釋−這裡我們有從1到4([1,Num(4)])的數字
序列中沒有數字能被P1整除
1和2能被P2整除
1和2能被P2整除,獲得2*2=4的利潤
輸入− num = 3, P1 = 1, P2 = 2, profit_P1 = 3, profit_P2 = 4
輸出− 最大化所有人員X的總利潤 10
解釋− 1、2和3都能被A整除。
2是給定範圍內唯一能被B整除的數。
2能被A和B整除。
1和3能被A整除,獲得2 * 3 = 6的利潤
2能被B整除,獲得1 * 4 = 4的利潤
2能被兩者整除,但為了最大化利潤,它被B而不是A整除。
下面程式中使用的方法如下:
我們得到了6個整數變數,包括正數範圍(Num)、表示第一個人P1、表示第二個人P2、表示第一個人利潤的profit_P1(即,如果給定數範圍內的數字能被P1整除,profit_P1增加),以及類似的profit_P2。
在主函式中呼叫了一個方法(profitMaximisation),它是所有計算的實用方法。
在函式內部可以看到,每個都能被P1和P2整除的數字,只有當該數字是P1或P2的最小公倍數的倍數時才成立。並且它應該除以能產生更多利潤的數字。
因此,這裡透過profit_P1 * (num / P1) + profit_P2 * (num / P2) – min(profit_P1, profit_P2) * (num / lcm(P1, P2))計算。
引入了一個CalculateGcd()方法來計算給定數字的最小公倍數。
最終輸出在主方法中捕獲並顯示給使用者。
示例
public class testClass{
static int CalculateGcd(int n1, int n2){
if (n2 == 0)
return n1;
return CalculateGcd(n2, n1 % n2);
}
static int profitMaximisation(int n, int a, int b, int x, int y){
int result = x * (n / a);
result += y * (n / b);
result -= Math.min(x, y) * (n / ((a * b) / CalculateGcd(a, b)));
return result;
}
public static void main(String[] args){
int num = 6, P1 = 6, P2 = 2, profit_P1 = 8, profit_P2 = 2;
System.out.println("Maximize the total profit of all the persons X "+profitMaximisation(num, P1, P2, profit_P1, profit_P2));
}
}輸出
如果執行以上程式碼,將生成以下輸出
Maximize the total profit of all the persons X 12
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP