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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Total number of unit cells covered by all given Rectangles
- Minimum number of squares whose sum equals to a given number N | Set-3
- Minimum number of squares whose sum equals to given number n
- Minimum number of squares whose sum equals to given number N | set 2
- Find the number of jumps to reach X in the number line from zero
- Number of perfect squares between two given numbers
- Paper Cut into Minimum Number of Squares
- Count number of squares in a rectangle
- Number of ways of writing N as a sum of 4 squares
- Check whether a number can be represented by sum of two squares
- Square pyramidal number (Sum of Squares)
- Check whether a number can be represented as difference of two squares
- Check whether a number can be represented by the product of two squares
- Count number less than N which are product of perfect squares
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.