How many integer points within the three points forming a triangle?

后端 未结 13 1279
一个人的身影
一个人的身影 2020-12-12 21:04

Actually this is a classic problem as SO user Victor put it (in another SO question regarding which tasks to ask during an interview).

I couldn\'t do it in an hour

13条回答
  •  攒了一身酷
    2020-12-12 21:49

    Here is a Python implementation of @Prabhala's solution:

    from collections import namedtuple
    from fractions import gcd
    
    
    def get_points(vertices):
        Point = namedtuple('Point', 'x,y')
        vertices = [Point(x, y) for x, y in vertices]
    
        a, b, c = vertices
    
        triangle_area = abs((a.x - b.x) * (a.y + b.y) + (b.x - c.x) * (b.y + c.y) + (c.x - a.x) * (c.y + a.y))
        triangle_area /= 2
        triangle_area += 1
    
        interior = abs(gcd(a.x - b.x, a.y - b.y)) + abs(gcd(b.x - c.x, b.y - c.y)) + abs(gcd(c.x - a.x, c.y - a.y))
        interior /= 2
    
        return triangle_area - interior
    

    Usage:

    print(get_points([(-1, -1), (1, 0), (0, 1)]))  # 1
    print(get_points([[2, 3], [6, 9], [10, 160]]))  # 289
    

提交回复
热议问题