Given 2 endpoints (x1, y1) and (x2, y2) of a line, the task is to determine the number of squares of the unit area that line will pass through.
Input: (x1 = 1, y1 = 1), (x2 = 4, y2 = 3)
In the diagram above the line is passing through 4 squares
Input: (x1 = 0, y1 = 0), (x2 = 2, y2 = 2)
Dx = (x2 - x1) Dy = (y2 - y1)
x = x1 + Dx * t y = y1 + Dy * t
We have to find (x, y) for t in (0, 1].
For, x and y to be integral Dx and Dy must be divisible by t. Also, t cannot be irrational since Dx and Dy are integers.
Therefore let t = p / q.
Dx and Dy must be divisible by q. So GCD of Dx and Dy must be q.
Or, q = GCD(Dx, Dy).
There are only GCD(Dx, Dy) smallest subproblems.
Below is the implementation of the above approach:
Time Complexity: O(1)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Number of unique rectangles formed using N unit squares
- Number of squares of maximum area in a rectangle
- Area of triangle formed by the axes of co-ordinates and a given straight line
- Determine whether the given integer N is a Peculiar Number or not
- Program to determine the Quadrant of a Complex number
- Determine whether a given number is a Hyperperfect Number
- Minimum number of squares whose sum equals to given number N | set 2
- Minimum number of squares whose sum equals to given number n
- Number of ways of writing N as a sum of 4 squares
- Paper Cut into Minimum Number of Squares
- Square pyramidal number (Sum of Squares)
- Count number of squares in a rectangle
- Check whether a number can be represented by sum of two squares
- Number of perfect squares between two given numbers
- Find the number of jumps to reach X in the number line from zero
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.