📌  相关文章
📜  将一个数字除以另一个可除的最小值

📅  最后修改于: 2021-04-22 01:32:44             🧑  作者: Mango

给定两个整数pq ,任务是找到最小可能数x ,以使q%x = 0x%p = 0 。如果条件不满足任何数字,则打印-1
例子:

方法:如果数字x满足给定条件,则很明显q将被p除,即q%p = 0,因为xp的倍数,而qx的倍数。
因此, x的最小可能值为pq的GCD,并且当q不能被p整除时,没有数字会满足给定条件。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the minimum valid number
// that satisfies the given conditions
int minValidNumber(int p, int q)
{
    // If possible
    if (q % p == 0)
        return __gcd(p, q);
    else
        return -1;
}
 
// Driver Code
int main()
{
    int p = 2, q = 6;
    cout << minValidNumber(p, q);
    return 0;
}


Java
//Java  implementation of the approach
 
import java.io.*;
 
class GFG {
     
    // Function to calculate gcd
    static int __gcd(int a, int b)
    {
         
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
     
        // base case
        if (a == b)
            return a;
     
        // a is greater
        if (a > b)
            return __gcd(a - b, b);
             
        return __gcd(a, b - a);
    }
 
// Function to return the minimum valid number
// that satisfies the given conditions
static int minValidNumber(int p, int q)
{
    // If possible
    if (q % p == 0)
        return __gcd(p, q);
    else
        return -1;
}
 
// Driver Code
    public static void main (String[] args) {
        int p = 2, q = 6;
        System.out.print(minValidNumber(p, q));
 
 
    // THis code is contributed by  Sachin.
    }
}


Python3
# Python3 implementation of the approach
from math import gcd
 
# Function to return the minimum
# valid number that satisfies the
# given conditions
def minValidNumber(p, q) :
 
    # If possible
    if (q % p == 0) :
        return gcd(p, q)
    else :
        return -1
 
# Driver Code
if __name__ == "__main__" :
 
    p, q = 2, 6;
    print(minValidNumber(p, q))
 
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
 
class GFG
{
    // Function to calculate gcd
    static int __gcd(int a, int b)
    {
          
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
      
        // base case
        if (a == b)
            return a;
      
        // a is greater
        if (a > b)
            return __gcd(a - b, b);
              
        return __gcd(a, b - a);
    }
 
// Function to return the minimum valid number
// that satisfies the given conditions
static int minValidNumber(int p, int q)
{
    // If possible
    if (q % p == 0)
        return __gcd(p, q);
    else
        return -1;
}
 
// Driver Code
public static void Main()
{
    int p = 2, q = 6;
    Console.Write(minValidNumber(p, q));
}
}
 
// THis code is contributed
// by Mukul Singh


PHP


Javascript


输出:
2