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)
- 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 a given number is a Hyperperfect Number
- Minimum number of squares whose sum equals to given number n
- Find the number of jumps to reach X in the number line from zero
- Check whether a number can be represented by sum of two squares
- Count number of squares in a rectangle
- Number of perfect squares between two given numbers
- Square pyramidal number (Sum of Squares)
- Number of ways of writing N as a sum of 4 squares
- Paper Cut into Minimum Number of Squares
- Count number less than N which are product of perfect squares
- Program to find number of squares in a chessboard
- Maximum number of squares that can fit in a right angle isosceles triangle
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.