给定XY空间中的两个点pointU和pointV ,我们需要找到一个具有整数坐标的点,该点位于通过点pointU和pointV的直线上。
例子:
If pointU = (1, -1 and pointV = (-4, 1)
then equation of line which goes
through these two points is,
2X + 5Y = -3
One point with integer co-ordinate which
satisfies above equation is (6, -3)
我们可以看到,一旦找到线方程,就可以将此问题视为扩展Euclid算法问题,其中我们知道AX + BY = C中的A,B,C,并希望从中找出X和Y的值。等式。
在上面的扩展Euclid方程中,C是A和B的gcd,因此从给定的两点找出线方程后,如果C不是gcd(A,B)的倍数,则可以得出结论:指定的行。如果C是g的倍数,那么我们可以按比例增加已建立的X和Y系数以满足实际方程式,这将是我们的最终答案。
// C++ program to get Integer point on a line
#include
using namespace std;
// Utility method for extended Euclidean Algorithm
int gcdExtended(int a, int b, int *x, int *y)
{
// Base Case
if (a == 0)
{
*x = 0;
*y = 1;
return b;
}
int x1, y1; // To store results of recursive call
int gcd = gcdExtended(b%a, a, &x1, &y1);
// Update x and y using results of recursive
// call
*x = y1 - (b/a) * x1;
*y = x1;
return gcd;
}
// method prints integer point on a line with two
// points U and V.
void printIntegerPoint(int c[], int pointV[])
{
// Getting coefficient of line
int A = (pointU[1] - pointV[1]);
int B = (pointV[0] - pointU[0]);
int C = (pointU[0] * (pointU[1] - pointV[1]) +
pointU[1] * (pointV[0] - pointU[0]));
int x, y; // To be assigned a value by gcdExtended()
int g = gcdExtended(A, B, &x, &y);
// if C is not divisible by g, then no solution
// is available
if (C % g != 0)
cout << "No possible integer point\n";
else
// scaling up x and y to satisfy actual answer
cout << "Integer Point : " << (x * C/g) << " "
<< (y * C/g) << endl;
}
// Driver code to test above methods
int main()
{
int pointU[] = {1, -1};
int pointV[] = {-4, 1};
printIntegerPoint(pointU, pointV);
return 0;
}
输出:
Integer Point : 6 -3