Determine the number of squares of unit area that a given line will pass through.
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.
Examples:
Input: (x1 = 1, y1 = 1), (x2 = 4, y2 = 3)
Output: 4
In the diagram above the line is passing through 4 squares
Input: (x1 = 0, y1 = 0), (x2 = 2, y2 = 2)
Output: 2
Approach:
Let,
Dx = (x2 - x1)
Dy = (y2 - y1)
Therefore,
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:
C++
#include<bits/stdc++.h>
using namespace std;
int noOfSquares( 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);
cout<<ans;
}
int main()
{
int x1 = 1, y1 = 1, x2 = 4, y2 = 3;
noOfSquares(x1, y1, x2, y2);
return 0;
}
|
Java
class GFG
{
static int __gcd( int a, int b)
{
if (b == 0 )
return a;
return __gcd(b, a % b);
}
static void noOfSquares( int x1, int y1,
int x2, int y2)
{
int dx = Math.abs(x2 - x1);
int dy = Math.abs(y2 - y1);
int ans = dx + dy - __gcd(dx, dy);
System.out.println(ans);
}
public static void main(String []args)
{
int x1 = 1 , y1 = 1 , x2 = 4 , y2 = 3 ;
noOfSquares(x1, y1, x2, y2);
}
}
|
Python3
from math import gcd
def noOfSquares(x1, y1, x2, y2) :
dx = abs (x2 - x1);
dy = abs (y2 - y1);
ans = dx + dy - gcd(dx, dy);
print (ans);
if __name__ = = "__main__" :
x1 = 1 ; y1 = 1 ; x2 = 4 ; y2 = 3 ;
noOfSquares(x1, y1, x2, y2);
|
C#
using System;
class GFG
{
static int __gcd( int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
static void noOfSquares( int x1, int y1,
int x2, int y2)
{
int dx = Math.Abs(x2 - x1);
int dy = Math.Abs(y2 - y1);
int ans = dx + dy - __gcd(dx, dy);
Console.WriteLine(ans);
}
static void Main()
{
int x1 = 1, y1 = 1, x2 = 4, y2 = 3;
noOfSquares(x1, y1, x2, y2);
}
}
|
PHP
<?php
function noOfSquares( $x1 , $y1 , $x2 , $y2 )
{
$dx = abs ( $x2 - $x1 );
$dy = abs ( $y2 - $y1 );
$ans = $dx + $dy - gcd( $dx , $dy );
echo ( $ans );
}
function gcd( $a , $b )
{
if ( $b == 0)
return $a ;
return gcd( $b , $a % $b );
}
$x1 = 1; $y1 = 1; $x2 = 4; $y2 = 3;
noOfSquares( $x1 , $y1 , $x2 , $y2 );
?>
|
Javascript
<script>
function __gcd(a, b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
function noOfSquares(x1, y1, x2, y2)
{
var dx = Math.abs(x2 - x1);
var dy = Math.abs(y2 - y1);
var ans = dx + dy - __gcd(dx, dy);
document.write(ans);
}
var x1 = 1, y1 = 1, x2 = 4, y2 = 3;
noOfSquares(x1, y1, x2, y2);
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Last Updated :
09 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...