Description
Let’s define a singular point on a line segment: a point that satisfies both X and Y coordinates as integers.Now,give you two points(x1,y1)and(x2,y2), Please find out the number of singular points between two points.
Input
It has multiple test data, input coordinates containing two points four integers. x1,y1,x2,y2(−10^9<=x1,y1,x2,y2<=10 9)
Output
Output the number of singular points
Sample Input 1
1 11 5 3
Sample Ouput 1
3
思路
1.给出的两点连成一条线段,要寻找在线段上的格点。
2.因为给出的坐标都是整数,寻找的格点即为在线段上并且横纵坐标都是整数的点。
3.问题可以转化为在一条线段上能找到几个底和高都是整数的最小三角形。可以求出横纵坐标差的绝对值a,b,当a,b分别除以它们的最大公约数时,可以得到最小三角形的底和高。所以a,b的最大公约数即为可以找到的最小三角形个数。
4.又因为寻找的是格点的个数,要用三角形个数减一。
代码
#include <stdio.h>
#include <math.h>
int gcd(int a, int b)
{
if (b == 0) return a;
return gcd(b, a % b);
}
int main(void)
{
int x1, y1, x2, y2;
while (scanf("%d%d%d%d", &x1, &y1, &x2, &y2) != EOF)
{
int a, b, c, d;
a = abs(x1 - x2);
b = abs(y1 - y2);
printf("%d\n", gcd(a, b) - 1);
}
return 0;
}