Input
The input contains several test cases.
Each test case contains four integers, x1,y1,x2,y2, all integers will between 0 and 50, inclusive..
The input will be terminated by EOF.
Output
For each test case, output the number of carrots that lie strictly on the line segment connecting these carrots.
Sample Input
1 1 5 5
0 0 1 1
50 48 0 0
0 0 42 36
Sample Output
3
0
1
5
代码实现:
// 两点之间整数点的个数
// 直接利用三点,两两之间连线的斜率相等进行比较 (这个想法挺奇妙)
// 一开始是想到要求出直线方程,但似乎实现起来不算数学那么容易
#include<iostream>
using namespace std;
int main() {
int x1, y1, x2, y2;
int a, b, c, d;
while (cin >> a >> b >> c >> d) {
x1 = a > c ? c : a;
x2 = a > c ? a : c;
y1 = b > d ? d : b;
y2 = b > d ? b : d;
// 横坐标和纵坐标相同的情况特殊处理
if (x1 == x2) {
if (y2 - y1 > 1) cout << y2 - y1 - 1 << endl;
else cout << '0' << endl;
} else if (y1 == y2) {
if (x2 - x1 > 1) cout << x2 - x1 - 1 << endl;
else cout << '0' << endl;
} else {
int total = 0;
for (int i = x1 + 1; i < x2; ++i) {
for (int j = y1 + 1; j < y2; ++j) {
double k1 = (double)(y2 - j)/(x2 - i);
double k2 = (double)(j - y1)/(i - x1);
if (k1 == k2) total++;
}
}
cout << total << endl;
}
}
}