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

后端 未结 13 1318
一个人的身影
一个人的身影 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:31

    Pick's theorem (http://en.wikipedia.org/wiki/Pick%27s_theorem) states that the surface of a simple polygon placed on integer points is given by:

    A = i + b/2 - 1
    

    Here A is the surface of the triangle, i is the number of interior points and b is the number of boundary points. The number of boundary points b can be calculated easily by summing the greatest common divisor of the slopes of each line:

    b =   gcd(abs(p0x - p1x), abs(p0y - p1y)) 
        + gcd(abs(p1x - p2x), abs(p1y - p2y)) 
        + gcd(abs(p2x - p0x), abs(p2y - p0y))
    

    The surface can also be calculated. For a formula which calculates the surface see https://stackoverflow.com/a/14382692/2491535 . Combining these known values i can be calculated by:

    i = A + 1 - b/2
    

提交回复
热议问题