给定代表“ ax – by = 0”中系数的两个值“ a”和“ b”,找到满足方程式的x和y的最小值。还可以假设x> 0,y> 0,a> 0和b> 0。
Input: a = 25, b = 35
Output: x = 7, y = 5
一个简单的解决方案是尝试从1、1开始的每个可能的x和y值,并在满足方程式时停止。
一个直接的解决方案是使用最小公倍数(LCM)。 “ a”和“ b”的LCM表示可以使双方相等的最小值。我们可以使用以下公式找到LCM。
LCM(a, b) = (a * b) / GCD(a, b)
可以使用Euclid算法计算最大公约数(GCD)。
C++
// C++ program to find the smallest values of x and y that
// satisfy "ax - by = 0"
#include
using namespace std;
// To find GCD using Eculcid's algorithm
int gcd(int a, int b)
{
if (b == 0)
return a;
return (gcd(b, a % b));
}
// Prints smallest values of x and y that
// satisfy "ax - by = 0"
void findSmallest(int a, int b)
{
// Find LCM
int lcm = (a * b) / gcd(a, b);
cout << "x = " << lcm / a
<< "\ny = " << lcm / b;
}
// Driver program
int main()
{
int a = 25, b = 35;
findSmallest(a, b);
return 0;
}
Java
// Java program to find the smallest values of
// x and y that satisfy "ax - by = 0"
class GFG {
// To find GCD using Eculcid's algorithm
static int gcd(int a, int b)
{
if (b == 0)
return a;
return (gcd(b, a % b));
}
// Prints smallest values of x and y that
// satisfy "ax - by = 0"
static void findSmallest(int a, int b)
{
// Find LCM
int lcm = (a * b) / gcd(a, b);
System.out.print("x = " + lcm / a
+ "\ny = " + lcm / b);
}
// Driver code
public static void main(String[] args)
{
int a = 25, b = 35;
findSmallest(a, b);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to find the
# smallest values of x and y that
# satisfy "ax - by = 0"
# To find GCD using Eculcid's algorithm
def gcd(a, b):
if (b == 0):
return a
return(gcd(b, a % b))
# Prints smallest values of x and y that
# satisfy "ax - by = 0"
def findSmallest(a, b):
# Find LCM
lcm = (a * b)/gcd(a, b)
print("x =", lcm / a, "\ny = ", lcm / b)
# Driver code
a = 25
b = 35
findSmallest(a, b)
# This code is contributed
# by Anant Agarwal.
C#
// C# program to find the smallest
// values of x and y that
// satisfy "ax - by = 0"
using System;
class GFG {
// To find GCD using
// Eculcid's algorithm
static int gcd(int a, int b)
{
if (b == 0)
return a;
return (gcd(b, a % b));
}
// Prints smallest values of x and
// y that satisfy "ax - by = 0"
static void findSmallest(int a, int b)
{
// Find LCM
int lcm = (a * b) / gcd(a, b);
Console.Write("x = " + lcm / a + "\ny = " + lcm / b);
}
// Driver code
public static void Main()
{
int a = 25, b = 35;
findSmallest(a, b);
}
}
// This code is contributed by Sam007.
PHP
Javascript
C
// Prints smallest values of x and y that
// satisfy "ax - by = 0"
void findSmallest(int a, int b)
{
// Find GCD
int g = gcd(a, b);
cout << "x = " << b / g
<< "\ny = " << a / g;
}
输出:
x = 7
y = 5
上面的findSmallest()代码可以减少:
Since ax - by = 0,
ax = by, which means x/y = b/a
So we can calculate gcd and directly do as -
Value of x = b / gcd;
Value of y = a / gcd;
C
// Prints smallest values of x and y that
// satisfy "ax - by = 0"
void findSmallest(int a, int b)
{
// Find GCD
int g = gcd(a, b);
cout << "x = " << b / g
<< "\ny = " << a / g;
}