给定两个整数p和q ,任务是找到最小可能数x ,以使q%x = 0和x%p = 0 。如果条件不满足任何数字,则打印-1 。
例子:
Input: p = 3, q = 99
Output: 3
99 % 3 = 0
3 % 3 = 0
Input: p = 2, q = 7
Output: -1
方法:如果数字x满足给定条件,则很明显q将被p除,即q%p = 0,因为x是p的倍数,而q是x的倍数。
因此, x的最小可能值为p和q的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