VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-integral-points-two-points/

⇱ Number of Integral Points between Two Points - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of Integral Points between Two Points

Last Updated : 23 Jul, 2025

Given two points p (x1, y1) and q (x2, y2), calculate the number of integral points lying on the line joining them.

Input: x1 = 2, y1 = 2, x2 = 5, y2 = 5

Output: 2

Explanation: There are only 2 integral points on the line joining (2,2) and (5,5). The points are (3,3) and (4,4).


Input: x1 = 1, y1 = 9, x2 = 8, y2 = 16

Output: 6

Explanation: There are 6 integral points on the line joining (1,9) and (8,16).

More Example: If points are (0, 2) and (4, 0), then the number of integral points lying on it is only one and that is (2, 1). 
Similarly, if points are (1, 9) and (8, 16), the integral points lying on it are 6 and they are (2, 10), (3, 11), (4, 12), (5, 13), (6, 14) and (7, 15). 

Simple Approach
Start from any of the given points, reach the other end point by using loops. For every point inside the loop, check if it lies on the line that joins given two points. If yes, then increment the count by 1. Time Complexity for this approach will be O(min(x2-x1, y2-y1)).

Optimal Approach

1. If the edge formed by joining p and q is parallel 
to the Y-axis, then the number of integral points
between the vertices is :
abs(p.y - q.y)-1

2. Similarly if edge is parallel to the X-axis, then
the number of integral points in between is :
abs(p.x - q.x)-1

3. Else, we can find the integral points between the
vertices using below formula:
GCD(abs(p.x - q.x), abs(p.y - q.y)) - 1


How does the GCD formula work?
The idea is to find the equation of the line in simplest form, i.e., in equation ax + by +c, coefficients a, b and c become co-prime. We can do this by calculating the GCD (greatest common divisor) of a, b and c and convert a, b and c in the simplest form. 
Then, the answer will be (difference of y coordinates) divided by (a) – 1. This is because after calculating ax + by + c = 0, for different y values, x will be number of y values which are exactly divisible by a.
Below is the implementation of above idea.

Output:

The number of integral points between (1, 9) and (8, 16) is 6

Time Complexity: O(log(min(a,b))), as we are using recursion to find the GCD.
Auxiliary Space: O(log(min(a,b))), for recursive stack space.


Reference : 
https://www.geeksforgeeks.org/dsa/count-integral-points-inside-a-triangle/
This article has been contributed by Paridhi Johari.

Comment
Article Tags: