给定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)
我们可以看到,一旦我们找到了直线方程,这个问题就可以看作是扩展欧几里德算法问题,我们知道 AX + BY = C 中的 A、B、C,我们想从方程。
在上面的扩展欧几里德方程中,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
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。