📌  相关文章
📜  求出最小数K,以使K%p = 0和q%K = 0

📅  最后修改于: 2021-05-08 18:15:05             🧑  作者: Mango

给定两个整数pq ,任务是找到最小的数K ,使得K%p = 0q%K = 0 。如果没有这样的K ,则打印-1

例子:

方法:为了使K成为可能,必须将q整除为p

  • 如果q%p = 0,则打印p
  • 否则打印-1

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
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


输出:
24