📌  相关文章
📜  当可除数为两个的数有关联的利润时,最大化利润

📅  最后修改于: 2021-04-24 20:04:20             🧑  作者: Mango

给定五个整数NABXY。任务是找到从[1,N]范围内的数字获得的最大利润。如果正数可被A整除,则利润增加X ;如果正数可被B整除,则利润增加Y。
注意:从正数获利最多只能相加一次。

例子:

方法:容易看出,只有数字为lcm(A,B)的倍数时,我们才能将数字除以AB。显然,该数字应除以可带来更多利润的数字。
因此,答案等于X *(N / A)+ Y *(N / B)– min(X,Y)*(N / lcm(A,B))

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the maximum profit
int maxProfit(int n, int a, int b, int x, int y)
{
    int res = x * (n / a);
    res += y * (n / b);
  
    // min(x, y) * n / lcm(a, b)
    res -= min(x, y) * (n / ((a * b) / __gcd(a, b)));
    return res;
}
  
// Driver code
int main()
{
    int n = 6, a = 6, b = 2, x = 8, y = 2;
    cout << maxProfit(n, a, b, x, y);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
  
static int __gcd(int a, int b) 
{ 
    if (b == 0) 
        return a; 
    return __gcd(b, a % b); 
      
} 
  
// Function to return the maximum profit
static int maxProfit(int n, int a, int b, 
                            int x, int y)
{
    int res = x * (n / a);
    res += y * (n / b);
  
    // min(x, y) * n / lcm(a, b)
    res -= Math.min(x, y) * (n / ((a * b) / __gcd(a, b)));
    return res;
}
  
// Driver code
public static void main (String[] args)
{
    int n = 6, a = 6, b = 2, x = 8, y = 2;
    System.out.println(maxProfit(n, a, b, x, y));
}
}
  
// This code is contributed by mits


Python3
# Python3 implementation of the approach 
from math import gcd
  
# Function to return the maximum profit 
def maxProfit(n, a, b, x, y) : 
      
    res = x * (n // a); 
    res += y * (n // b); 
  
    # min(x, y) * n / lcm(a, b) 
    res -= min(x, y) * (n // ((a * b) // 
                           gcd(a, b))); 
    return res; 
  
# Driver code 
if __name__ == "__main__" : 
  
    n = 6 ;a = 6; b = 2; x = 8; y = 2; 
      
    print(maxProfit(n, a, b, x, y)); 
      
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
  
class GFG
{
  
static int __gcd(int a, int b) 
{ 
    if (b == 0) 
        return a; 
    return __gcd(b, a % b); 
      
} 
  
// Function to return the maximum profit
static int maxProfit(int n, int a, int b, int x, int y)
{
    int res = x * (n / a);
    res += y * (n / b);
  
    // min(x, y) * n / lcm(a, b)
    res -= Math.Min(x, y) * (n / ((a * b) / __gcd(a, b)));
    return res;
}
  
// Driver code
static void Main()
{
    int n = 6, a = 6, b = 2, x = 8, y = 2;
    Console.WriteLine(maxProfit(n, a, b, x, y));
}
}
  
// This code is contributed by mits


PHP


输出:
12