1397. Lattice Points on a Ring
A circular fountain of radius r is centred at the origin of a city map, and the planners want to place a lamp post at every intersection of the integer street grid that lies exactly on its rim. Count the integer points (x, y) that satisfy x^2 + y^2 = r^2 exactly, with no rounding tolerance.
Walk x from -r to r. For each x, take t = r^2 - x^2 and decide whether t is a perfect square using an exact 64-bit integer square root (do not trust a floating-point root without correcting it). If t = y^2, add 1 when y = 0 and 2 otherwise, since y and -y are different points. For r = 0 the only point is the origin, so the answer is 1. Return the total as an int. The intended solution runs in O(r) time and O(1) extra space.
Example 1
- Input:
- r = 5
- Output:
- 12
- Explanation:
The points (0,5), (5,0), (3,4), (4,3) and their sign variants give 12 points.
Example 2
- Input:
- r = 1
- Output:
- 4
- Explanation:
Only (1,0), (-1,0), (0,1) and (0,-1) lie on the unit ring.
Constraints
0 ≤ r ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(r)
- Space
- O(1)