Minimice el costo de hacer que X e Y sean iguales en incrementos dados

Dados dos enteros X e Y , la tarea es hacer que ambos enteros sean iguales realizando las siguientes operaciones cualquier número de veces:

  • Aumenta X por M veces. Costo = M – 1 .
  • Aumenta Y por N veces. Costo = N – 1 .

Ejemplos:

Entrada: X = 2, Y = 4 
Salida:
Explicación: 
Incrementar X por 2 veces. Por lo tanto, X = 2 * 2 = 4. Costo = 1. 
Claramente, X = Y. Por lo tanto, costo total = 1.

Entrada: X = 4, Y = 6 
Salida:
Explicación: 
Aumenta X 3 veces, X = 3 * 4 = 12. Costo = 2. 
Aumenta Y 2 veces, Y = 2 * 6 = 12. Costo = 1. 
Claramente, X = Y. Por lo tanto, costo total = 2 + 1 = 3.

Enfoque ingenuo: siga los pasos a continuación para resolver el problema:

  1. Para cada valor de X , si Y es menor que X , incremente Y y actualice el costo.
  2. Si X = Y , imprima el costo total.
  3. Si X < Y , entonces incremente X y actualice el costo.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to find minimum cost
// to make x and y equal
int minimumCost(int x, int y)
{
    int costx = 0, dup_x = x;
 
    while (true) {
 
        int costy = 0, dup_y = y;
 
        // Check if it possible
        // to make x == y
        while (dup_y != dup_x
               && dup_y < dup_x) {
            dup_y += y;
            costy++;
        }
 
        // Iif both are equal
        if (dup_x == dup_y)
            return costx + costy;
 
        // Otherwise
        else {
 
            // Increment cost of x
            // by 1 and dup_x by x
            dup_x += x;
            costx++;
        }
    }
}
 
// Driver Code
int main()
{
    int x = 5, y = 17;
 
    // Returns the required minimum cost
    cout << minimumCost(x, y) << endl;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to find minimum cost
// to make x and y equal
static int minimumCost(int x, int y)
{
    int costx = 0, dup_x = x;
    while (true)
    {
        int costy = 0, dup_y = y;
 
        // Check if it possible
        // to make x == y
        while (dup_y != dup_x
               && dup_y < dup_x)
        {
            dup_y += y;
            costy++;
        }
 
        // Iif both are equal
        if (dup_x == dup_y)
            return costx + costy;
 
        // Otherwise
        else {
 
            // Increment cost of x
            // by 1 and dup_x by x
            dup_x += x;
            costx++;
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int x = 5, y = 17;
 
    // Returns the required minimum cost
    System.out.print(minimumCost(x, y) +"\n");
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program for the above approach
 
# Function to find minimum cost
# to make x and y equal
def minimumCost(x, y):
     
    costx, dup_x = 0, x
 
    while (True):
        costy, dup_y = 0, y
         
        # Check if it possible
        # to make x == y
        while (dup_y != dup_x and
               dup_y < dup_x):
            dup_y += y
            costy += 1
 
        # If both are equal
        if (dup_x == dup_y):
            return costx + costy
 
        # Otherwise
        else:
             
            # Increment cost of x
            # by 1 and dup_x by x
            dup_x += x
            costx += 1
 
# Driver Code
if __name__ == '__main__':
     
    x, y = 5, 17
 
    # Returns the required minimum cost
    print(minimumCost(x, y))
 
# This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
class GFG
{
 
  // Function to find minimum cost
  // to make x and y equal
  static int minimumCost(int x, int y)
  {
    int costx = 0, dup_x = x;
    while (true)
    {
      int costy = 0, dup_y = y;
 
      // Check if it possible
      // to make x == y
      while (dup_y != dup_x
             && dup_y < dup_x)
      {
        dup_y += y;
        costy++;
      }
 
      // Iif both are equal
      if (dup_x == dup_y)
        return costx + costy;
 
      // Otherwise
      else {
 
        // Increment cost of x
        // by 1 and dup_x by x
        dup_x += x;
        costx++;
      }
    }
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int x = 5, y = 17;
 
    // Returns the required minimum cost
    Console.Write(minimumCost(x, y) +"\n");
  }
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
// javascript program for the above approach
 
    // Function to find minimum cost
    // to make x and y equal
    function minimumCost(x, y)
    {
        var costx = 0, dup_x = x;
        while (true)
        {
            var costy = 0, dup_y = y;
 
            // Check if it possible
            // to make x == y
            while (dup_y != dup_x && dup_y < dup_x) {
                dup_y += y;
                costy++;
            }
 
            // Iif both are equal
            if (dup_x == dup_y)
                return costx + costy;
 
            // Otherwise
            else {
 
                // Increment cost of x
                // by 1 and dup_x by x
                dup_x += x;
                costx++;
            }
        }
    }
 
    // Driver Code
        var x = 5, y = 17;
 
        // Returns the required minimum cost
        document.write(minimumCost(x, y) + "\n");
 
// This code is contributed by Rajput-Ji
</script>
Producción: 

20

 

Complejidad de Tiempo: O((costx + costy)*Y)
Espacio Auxiliar: O(1)

Método Eficiente: La idea aquí es utilizar el concepto de LCM . El costo mínimo de fabricar tanto X como Y será igual a su MCM. Pero esto no es suficiente. Reste los valores iniciales de X e Y para evitar sumarlos al calcular las respuestas.
Siga los pasos a continuación para resolver el problema:

  1. Encuentre MCM de X e Y.
  2. Reste el valor de X e Y de MCM.
  3. Ahora, divida el MCM entre X e Y , y la suma de sus valores es la respuesta requerida.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to find gcd of x and y
int gcd(int x, int y)
{
    if (y == 0)
        return x;
    return gcd(y, x % y);
}
 
// Function to find lcm of x and y
int lcm(int x, int y)
{
    return (x * y) / gcd(x, y);
}
 
// Function to find minimum Cost
int minimumCost(int x, int y)
{
    int lcm_ = lcm(x, y);
 
    // Subtracted initial cost of x
    int costx = (lcm_ - x) / x;
 
    // Subtracted initial cost of y
    int costy = (lcm_ - y) / y;
    return costx + costy;
}
 
// Driver Code
int main()
{
    int x = 5, y = 17;
 
    // Returns the minimum cost required
    cout << minimumCost(x, y) << endl;
}

Java

// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find gcd of x and y
static int gcd(int x, int y)
{
    if (y == 0)
        return x;
    return gcd(y, x % y);
}
 
// Function to find lcm of x and y
static int lcm(int x, int y)
{
    return (x * y) / gcd(x, y);
}
 
// Function to find minimum Cost
static int minimumCost(int x, int y)
{
    int lcm_ = lcm(x, y);
 
    // Subtracted initial cost of x
    int costx = (lcm_ - x) / x;
 
    // Subtracted initial cost of y
    int costy = (lcm_ - y) / y;
    return costx + costy;
}
 
// Driver Code
public static void main(String[] args)
{
    int x = 5, y = 17;
 
    // Returns the minimum cost required
    System.out.print(minimumCost(x, y) +"\n");
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program for the above approach
 
# Function to find gcd of x and y
def gcd(x, y):
     
    if (y == 0):
        return x
         
    return gcd(y, x % y)
 
# Function to find lcm of x and y
def lcm(x, y):
 
    return (x * y) // gcd(x, y)
 
# Function to find minimum Cost
def minimumCost(x, y):
     
    lcm_ = lcm(x, y)
 
    # Subtracted initial cost of x
    costx = (lcm_ - x) // x
 
    # Subtracted initial cost of y
    costy = (lcm_ - y) // y
     
    return costx + costy
 
# Driver Code
if __name__ == "__main__":
     
    x = 5
    y = 17
 
    # Returns the minimum cost required
    print(minimumCost(x, y))
 
# This code is contributed by chitranayal

C#

// C# program for the above approach
using System;
class GFG
{
 
// Function to find gcd of x and y
static int gcd(int x, int y)
{
    if (y == 0)
        return x;
    return gcd(y, x % y);
}
 
// Function to find lcm of x and y
static int lcm(int x, int y)
{
    return (x * y) / gcd(x, y);
}
 
// Function to find minimum Cost
static int minimumCost(int x, int y)
{
    int lcm_ = lcm(x, y);
 
    // Subtracted initial cost of x
    int costx = (lcm_ - x) / x;
 
    // Subtracted initial cost of y
    int costy = (lcm_ - y) / y;
    return costx + costy;
}
 
// Driver Code
public static void Main(String[] args)
{
    int x = 5, y = 17;
 
    // Returns the minimum cost required
    Console.Write(minimumCost(x, y) +"\n");
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
// javascript program for the above approach
 
    // Function to find gcd of x and y
    function gcd(x , y) {
        if (y == 0)
            return x;
        return gcd(y, x % y);
    }
 
    // Function to find lcm of x and y
    function lcm(x , y) {
        return (x * y) / gcd(x, y);
    }
 
    // Function to find minimum Cost
    function minimumCost(x , y) {
        var lcm_ = lcm(x, y);
 
        // Subtracted initial cost of x
        var costx = (lcm_ - x) / x;
 
        // Subtracted initial cost of y
        var costy = (lcm_ - y) / y;
        return costx + costy;
    }
 
    // Driver Code
     
        var x = 5, y = 17;
 
        // Returns the minimum cost required
        document.write(minimumCost(x, y) + "\n");
 
// This code contributed by gauravrajput1
</script>
Producción: 

20

 

Complejidad de tiempo: O(log(min(x, y))
Espacio auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por shekabhi1208 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *