Determine the number of squares of unit area that a line will pass through in C++?


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;
}

Example

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

 Live Demo

#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;
}

Output

The above code will produce the following output −

The line passes through 9 squares

Updated on: 16-Jan-2021

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements