Cuente los posibles valores de K tales que A%K = B%K

Dados dos enteros A y B , la tarea es contar los posibles valores de K tales que A%K = B%K . Si el conteo es infinito, imprime -1 .

Ejemplos:

Entrada: A = 2, B = 4
Salida: 2
Explicación: El conjunto de todos los valores posibles de K es {1, 2}. 
Como 2%1 = 4%1 = 0 y 2%2 = 4%2 = 0.

Entrada: A = 5, B = 5
Salida: -1
Explicación: Hay infinitos valores de K ya que todos los valores enteros posibles de K satisfacen la condición dada.

 

Enfoque: El problema dado se puede resolver utilizando la siguiente observación de que todos los valores de A y B se pueden dividir en los siguientes dos casos:

  • El caso donde A = B . En tales casos, todos los valores enteros posibles de K son una respuesta válida. Por lo tanto, el valor de la cuenta requerida es infinito.
  • El caso donde A > B . En tales casos, se puede observar que un valor de K es válido si K divide (A – B) . Para casos con B > A , simplemente intercambie los valores de A y B .

Por lo tanto, calcule todos los valores posibles de K tal que divida (A – B) por completo cuál es el valor requerido.

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

C++14

// C++ Program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of the
// values of K such that A%K = B%K
int countInt(int A, int B)
{
    // If the count is Infinite
    if (A == B)
        return -1;
 
    int diff = abs(A - B);
 
    // Stores the required count
    int count = 0;
 
    // Loop to calculate all the
    // divisors of diff
    for (int i = 1; i * i <= diff; i++) {
        if (diff % i == 0) {
 
            // Increment count for i
            if (diff == i * i)
                count++;
 
            // Increment count for i
            // and diff / i both
            else
                count += 2;
        }
    }
 
    // Return Answer
    return count;
}
 
// Driver code
int main()
{
    int A = 2, B = 4;
    cout << countInt(A, B);
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to find the count of the
  // values of K such that A%K = B%K
  static int countInt(int A, int B)
  {
     
    // If the count is Infinite
    if (A == B)
      return -1;
 
    int diff = Math.abs(A - B);
 
    // Stores the required count
    int count = 0;
 
    // Loop to calculate all the
    // divisors of diff
    for (int i = 1; i * i <= diff; i++) {
      if (diff % i == 0) {
 
        // Increment count for i
        if (diff == i * i)
          count++;
 
        // Increment count for i
        // and diff / i both
        else
          count += 2;
      }
    }
 
    // Return Answer
    return count;
  }
 
  // Driver code
  public static void main (String[] args) {
 
    int A = 2, B = 4;
    System.out.print(countInt(A, B));
  }
}
 
// This code is contributed by hrithikgarg03188.

Python3

# Python code for the above approach
 
# Function to find the count of the
# values of K such that A%K = B%K
def countInt(A, B):
   
    # If the count is Infinite
    if (A == B):
        return -1;
 
    diff = abs(A - B);
 
    # Stores the required count
    count = 0;
 
    # Loop to calculate all the
    # divisors of diff
    i = 1;
    while((i * i) <= diff):
        if (diff % i == 0):
 
            # Increment count for i
            if (diff == i * i):
                count += 1
 
            # Increment count for i
            # and diff / i both
            else:
                count += 2;
        i += 1
    # Return Answer
    return count;
 
# Driver code
 
A = 2
B = 4
print(countInt(A, B));
 
# This code is contributed by Saurabh Jaiswal

C#

// C# Program of the above approach
using System;
class GFG {
    // Function to find the count of the
    // values of K such that A%K = B%K
    static int countInt(int A, int B)
    {
        // If the count is Infinite
        if (A == B)
            return -1;
 
        int diff = Math.Abs(A - B);
 
        // Stores the required count
        int count = 0;
 
        // Loop to calculate all the
        // divisors of diff
        for (int i = 1; i * i <= diff; i++) {
            if (diff % i == 0) {
 
                // Increment count for i
                if (diff == i * i)
                    count++;
 
                // Increment count for i
                // and diff / i both
                else
                    count += 2;
            }
        }
 
        // Return Answer
        return count;
    }
 
    // Driver code
    public static int Main()
    {
        int A = 2, B = 4;
        Console.Write(countInt(A, B));
        return 0;
    }
}
 
// This code is contributed by Taranpreet

Javascript

<script>
      // JavaScript code for the above approach
 
      // Function to find the count of the
      // values of K such that A%K = B%K
      function countInt(A, B) {
          // If the count is Infinite
          if (A == B)
              return -1;
 
          let diff = Math.abs(A - B);
 
          // Stores the required count
          let count = 0;
 
          // Loop to calculate all the
          // divisors of diff
          for (let i = 1; i * i <= diff; i++) {
              if (diff % i == 0) {
 
                  // Increment count for i
                  if (diff == i * i)
                      count++;
 
                  // Increment count for i
                  // and diff / i both
                  else
                      count += 2;
              }
          }
 
          // Return Answer
          return count;
      }
 
      // Driver code
 
      let A = 2, B = 4;
      document.write(countInt(A, B));
 
       // This code is contributed by Potta Lokesh
  </script>
Producción

2

Complejidad de Tiempo: O(√(A – B))
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por prophet1999 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 *