📌  相关文章
📜  找到最小的数 K 使得 K % p = 0 和 q % K = 0

📅  最后修改于: 2021-10-27 03:28:51             🧑  作者: 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


Javascript


输出:
24

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程