给定直线的2个端点(x1,y1)和(x2,y2) ,任务是确定直线将通过的单位面积的平方数。
例子:
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
方法:
让,
Dx = (x2 - x1)
Dy = (y2 - y1)
所以,
x = x1 + Dx * t
y = y1 + Dy * t
我们必须在(0,1]中找到t的(x,y)。
为了使x和y成为整数,Dx和Dy必须被t整除。而且,由于Dx和Dy是整数,因此t不能是非理性的。
因此,令t = p / q 。
Dx和Dy必须被q整除。因此Dx和Dy的GCD必须为q。
或者,q = GCD(Dx,Dy)。
只有GCD(Dx,Dy)最小的子问题。
下面是上述方法的实现:
C++
#include
using namespace std;
// Function to return the required position
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<
Java
// Java program to determine the numer
// of squares that line will pass through
class GFG
{
static int __gcd(int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Function to return the required position
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);
}
// Driver Code
public static void main(String []args)
{
int x1 = 1, y1 = 1, x2 = 4, y2 = 3;
noOfSquares(x1, y1, x2, y2);
}
}
// This code contributed by Rajput-Ji
Python3
# Python3 program to determine the number
# of squares that line will pass through
from math import gcd
# Function to return the required position
def noOfSquares(x1, y1, x2, y2) :
dx = abs(x2 - x1);
dy = abs(y2 - y1);
ans = dx + dy - gcd(dx, dy);
print(ans);
# Driver Code
if __name__ == "__main__" :
x1 = 1; y1 = 1; x2 = 4; y2 = 3;
noOfSquares(x1, y1, x2, y2);
# This code is contributed by Ryuga
C#
using System;
class GFG
{
static int __gcd(int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Function to return the required position
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);
}
// Driver Code
static void Main()
{
int x1 = 1, y1 = 1, x2 = 4, y2 = 3;
noOfSquares(x1, y1, x2, y2);
}
}
// This code is contributed by mits
PHP
Javascript
输出:
4
时间复杂度: O(1)