Redaksiya
If and are integer endpoints of the segment, then the number of integer points on it is equal to .
Since the coordinates of the segment endpoints do not exceed in absolute value, the absolute difference of coordinates and does not exceed . For example, if and , then . Therefore, -bit integer type should be used for computations.
Example
For the first example, the answer is
For the second example, the answer is
Algorithm realization
The gcd function returns the greatest common divisor of the numbers and .
int gcd(int a, int b) { return (!b) ? a : gcd(b,a % b); }
Read the input data.
scanf("%lld %lld %lld %lld",&x1,&y1,&x2,&y2);
Compute the answer using the formula and print it.
res = gcd(abs(x2 - x1), abs(y2 - y1)) + 1; printf("%lld\n",res);
Java realization
public class Main {
The gcd function returns the greatest common divisor of the numbers and .
static long gcd(long a, long b) { if (b == 0) return a; return gcd(b,a % b); } public static void main(String[] args) { Scanner con = new Scanner(System.in);
Read the input data.
long x1 = con.nextLong(), y1 = con.nextLong(), x2 = con.nextLong(), y2 = con.nextLong();
Compute the answer using the formula and print it.
long res = 1 + gcd(Math.abs(x2 - x1), Math.abs(y2 - y1)); System.out.println(res); } }
Python realization
The gcd function returns the greatest common divisor of the numbers and .
def gcd(a, b): if a == 0: return b if b == 0: return a if a > b: return gcd(a % b, b) return gcd(a, b % a)
Read the input data.
x1, y1, x2, y2 = map(int, input().split())
Compute the answer using the formula and print it.
res = gcd(abs(x2 - x1), abs(y2 - y1)) + 1 print(res)
Python realization — gcd
To compute the greatest common divisor (GCD) of two numbers, let's use the gcd function built into the Python language.
import math
Read the input data.
x1, y1, x2, y2 = map(int, input().split())
Compute the answer using the formula and print it.
res = math.gcd(abs(x2 - x1), abs(y2 - y1)) + 1 print(res)