📜  给定A和B中X的X的最小正整数可能值X = P * A + Q * B

📅  最后修改于: 2021-05-08 16:29:30             🧑  作者: Mango

给定A和B的值,找到可在等式X = P * A + P * B中获得的X的最小正整数值,此处P和Q可以为零或任何正整数或负整数。
例子:

Input: A = 3
        B = 2
Output: 1

Input: A = 2
         B = 4 
Output: 2

基本上,我们需要找到P和Q,使得P * A> P * B和P * A – P * B是最小正整数。通过计算两个数字的GCD可以轻松解决此问题。
例如:

For A = 2 
And B = 4
Let P  = 1
And Q = 0            
X = P*A + Q*B
  = 1*2 + 0*4
  = 2 + 0
  = 2 (i. e GCD of 2 and 4)

For A = 3
and B = 2
let P = -1
And Q = 2
X = P*A + Q*B
  = -1*3 + 2*2
  = -3 + 4
  = 1 ( i.e GCD of 2 and 3 )

下面是上述想法的实现:

CPP
// CPP Program to find
// minimum value of X
// in equation X = P*A + Q*B
  
#include 
using namespace std;
  
// Utility function to calculate GCD
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
  
// Driver Code
int main()
{
    int a = 2;
    int b = 4;
    cout << gcd(a, b);
    return 0;
}


Java
// Java Program to find
// minimum value of X
// in equation X = P*A + Q*B
import java.util.*;
import java.lang.*;
  
class GFG {
    // utility function to calculate gcd
  
    public static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
  
        return gcd(b % a, a);
    }
  
    // Driver Program
    public static void main(String[] args)
    {
        int a = 2;
        int b = 4;
  
        System.out.println(gcd(a, b));
    }
}


Python3
# Python3 Program to find
# minimum value of X
# in equation X = P * A + Q * B
  
# Function to return gcd of a and b
  
  
def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)
  
  
a = 2
b = 4
print(gcd(a, b))


C#
// CSHARP Program to find
// minimum value of X
// in equation X = P*A + Q*B
using System;
  
class GFG {
    // function to get gcd of a and b
    public static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
  
        return gcd(b % a, a);
    }
  
    // Driver Code
    static public void Main()
    {
        int a = 2;
        int b = 4;
        Console.WriteLine(gcd(a, b));
    }
}


PHP
// PHP Program to find 
// minimum value of X
// in equation X = P*A + Q*B 
  


输出
2