- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

The objective is to determine the number of squares a line will pass through given two endpoints (x1,y1) and (x2,y2).

To find the number of squares through which our line pass we need to find : difference between the x points (dx) = x2-x1, difference between the y points (dy) = y2-y1, adding the dx and dy and subtracting by their gcd (result) = dx + dy – gcd(dx,dy).

The unitSquares(int x1, int y1, int x2, int y2) function takes four values x1,y1 and x2,y2. The absolute difference between the x2 and x1 and the absolute difference between the y2 and y1 are calculated. The dx and dy are added and subtracted from the gcd of dx,dy. The result is stored in ans and returned to main for printing.

int unitSquares(int x1, int y1, int x2, int y2){ int dx = abs(x2 - x1); int dy = abs(y2 - y1); int ans = dx + dy - __gcd(dx, dy); return ans; }

Let us look at the following implementation to determine the number of squares unit area that a line will pass through.

#include<iostream> #include <algorithm> using namespace std; int unitSquares(int x1, int y1, int x2, int y2){ int dx = abs(x2 - x1); int dy = abs(y2 - y1); int ans = dx + dy - __gcd(dx, dy); return ans; } int main(){ int x1 = 3, y1 = 3, x2 = 12, y2 = 6; cout<<"The line passes through "<<unitSquares(x1, y1, x2, y2)<<" squares "; return 0; }

The above code will produce the following output −

The line passes through 9 squares

- Related Questions & Answers
- Area of squares formed by joining midpoints repeatedly in C?
- Count number of squares in a rectangle in C++
- Maximum number of squares that can fit in a right angle isosceles triangle in C++
- Factors that Determine the Capital Structure of a Company
- Area of squares formed by joining mid points repeatedly in C Program?
- Program to find number of squares in a chessboard in C++
- Count the total number of squares that can be visited by Bishop in one move in C++
- 8086 program to determine squares of numbers in an array of n numbers
- Smallest number of perfect squares that sums up to n in JavaScript
- Check if a line passes through the origin in C++
- Print multiples of Unit Digit of Given Number in C Program
- Iterate through Java Unit Tuple
- Maximum number of parallelograms that can be made using the given length of line segments in C++
- Possible number of Rectangle and Squares with the given set of elements in C++
- Maximum number of 2×2 squares that can be fit inside a right isosceles triangle in C

Advertisements