Dados dos enteros p y q , la tarea es encontrar el número K más pequeño tal que K % p = 0 y q % K = 0 . Si tal K no es posible, imprima -1 .
Ejemplos:
Entrada: p = 2, q = 8
Salida: 2
2 % 2 = 0 y 8 % 2 = 0
Entrada: p = 5, q = 14
Salida: -1
Enfoque: Para que K sea posible, q debe ser divisible por p .
- Si q % p = 0 entonces imprima p
- De lo contrario imprime -1 .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the minimum // value K such that K % p = 0 // and q % k = 0 int getMinVal(int p, int q) { // If K is possible if (q % p == 0) return p; // No such K is possible return -1; } // Driver code int main() { int p = 24, q = 48; cout << getMinVal(p, q); return 0; }
Java
// Java implementation of the approach import java.io.*; class GFG { // Function to return the minimum // value K such that K % p = 0 // and q % k = 0 static int getMinVal(int p, int q) { // If K is possible if (q % p == 0) return p; // No such K is possible return -1; } // Driver code public static void main (String[] args) { int p = 24, q = 48; System.out.println(getMinVal(p, q)); } } // This code is contributed by jit_t.
Python3
# Python3 implementation of the approach # Function to return the minimum # value K such that K % p = 0 # and q % k = 0 def getMinVal(p, q): # If K is possible if q % p == 0: return p # No such K is possible return -1 # Driver code p = 24; q = 48 print(getMinVal(p, q)) # This code is contributed # by Shrikant13
C#
// C# implementation of the approach using System; class GFG { // Function to return the minimum // value K such that K % p = 0 // and q % k = 0 static int getMinVal(int p, int q) { // If K is possible if (q % p == 0) return p; // No such K is possible return -1; } // Driver code public static void Main () { int p = 24, q = 48; Console.WriteLine(getMinVal(p, q)); } } // This code is contributed // by Code_Mech.
PHP
<?php // PHP implementation of the approach // Function to return the minimum // value K such that K % p = 0 // and q % k = 0 function getMinVal($p, $q) { // If K is possible if ($q % $p == 0) return $p; // No such K is possible return -1; } // Driver code $p = 24; $q = 48; echo getMinVal($p, $q); // This code is contributed by ajit. ?>
Javascript
<script> // Javascript implementation of the above approach // Function to return the minimum // value K such that K % p = 0 // and q % k = 0 function getMinVal(p, q) { // If K is possible if (q % p == 0) return p; // No such K is possible return -1; } // driver program let p = 24, q = 48; document.write(getMinVal(p, q)); </script>
Producción:
24
Complejidad de Tiempo : O(1)
Espacio Auxiliar : O(1), ya que no se ha tomado ningún espacio extra.