Counting integer points inside a sphere of radius R and dimension D

前端 未结 3 1258
心在旅途
心在旅途 2021-01-03 15:29

I am trying to write an efficient algorithm that counts the number of points inside a Sphere of Radius R and Dimension D. The sphere is always at the origin. Suppose we have

3条回答
  •  萌比男神i
    2021-01-03 16:09

    For 2D case this is Gauss's circle problem. One possible formula:

    N(r) = 1 + 4 * r + 4 * Sum[i=1..r]{Floor(Sqrt(r^2-i^2))}
    

    (central point + four quadrants, 4*r for points at the axis, others for in-quadrant region).

    Note that there is no known simple closed math expression for 2D case.

    In general your idea with quadrants, octants etc is right, but checking all the points is too expensive.

    One might find the number of ways to compose all squares from 0 to r^2 from 1..D integer squares (extension of (4) formula).

    Note that combinatorics would help to make calculation faster. For example, it is enough to find the number of ways to make X^2 from D natural squares, and multiply by 2^D (different sign combinations); find the number of ways to make X^2 from D-1 natural squares, and multiply by D*2^(D-1) (different sign combinations + D places for zero addend) etc

    Example for D=2, R=3

    addends: 0,1,4,9
    possible sum     compositions    number of variants        
    0               0+0             1
    1               0+1,1+0         2*2=4
    2               1+1             4      
    4               0+4,4+0         2*2=4
    5               1+4,4+1         2*4=8  
    8               4+4             4
    9               0+9,9+0         2*2=4
    -------------------------------------
                                    29
    

提交回复
热议问题