给定一条线的 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 整除。此外,t 不能是无理数,因为 Dx 和 Dy 是整数。
因此让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 number
// 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)