我正在尝试解决这个编码难题:“给定一个对数组,每对 (x, y),都是整数,表示笛卡尔坐标平面中某个点的坐标,找出多组共线的三点。”
事实证明下面这个是正确的算法:
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
def how_many_3point_in_line( points ):
ans = 0
n = len( points )
for i in range( n - 2 ):
slopes = defaultdict( int )
for j in range( i + 1, n ):
dy, dx = points[i][1] - points[j][1], points[i][0] - points[j][0]
gcd_num = gcd( dx, dy )
slopes[( dy // gcd_num, dx // gcd_num )] += 1
for _, occ in slopes.items():
ans += math.comb( occ, 2 )
return ans
显然,gcd 用于表示斜率,它解决了什么问题?