Unit circles through three of n points
Show that n points in the plane have only o(n²) unit circles passing through three of them; the best construction gives n^{3/2}.

| 1 | #!/usr/bin/env python3 |
| 2 | """Count distinct circles of radius exactly 1 through >= 3 of n rational points. |
| 3 | |
| 4 | Usage: python3 count.py <configuration.json> |
| 5 | |
| 6 | Exact integer arithmetic only: no floats, no fractions.Fraction, no square |
| 7 | roots taken as values -- square roots appear only as perfect-square tests. |
| 8 | |
| 9 | Derivation used |
| 10 | --------------- |
| 11 | 1. Common scale. Let L be the lcm of the denominators of every coordinate, so |
| 12 | point i is the integer pair (Xi, Yi) meaning (Xi/L, Yi/L). In the scaled |
| 13 | plane the unit circle has radius exactly L and every comparison is integral. |
| 14 | |
| 15 | 2. Circumcenter. For a non-collinear triple take u = (a, b) = Pj - Pi, |
| 16 | v = (c, d) = Pk - Pi and D = ad - bc != 0. "C is equidistant from Pi, Pj" |
| 17 | is the linear equation 2 u.(C - Pi) = |u|^2, likewise for v; Cramer's rule |
| 18 | on the two equations gives |
| 19 | C = (Xi + P/(2D), Yi + Q/(2D)), |
| 20 | P = d(a^2 + b^2) - b(c^2 + d^2), Q = a(c^2 + d^2) - c(a^2 + b^2). |
| 21 | The squared distance to Pi is then (P^2 + Q^2)/(4 D^2), so the circle has |
| 22 | radius 1 in the original plane iff its scaled radius is L, iff |
| 23 | P^2 + Q^2 == 4 D^2 L^2. (no sqrt) |
| 24 | That identity is necessary and sufficient; it is preceded by the same |
| 25 | congruence modulo two primes, which is only necessary, so the pre-filter can |
| 26 | drop a triple only when the exact test would reject it too. It exists |
| 27 | because the common denominator of many large denominators can make every |
| 28 | integer thousands of digits long even though no circle is ever found. |
| 29 | |
| 30 | 3. Dedup. The center is stored as the canonical integer triple |
| 31 | (Nx, Ny, 2D) reduced by g = gcd(|Nx|, |Ny|, |2D|) with positive third |
| 32 | entry, Nx = 2D*Xi + P, Ny = 2D*Yi + Q. A canonical triple is unique for a |
| 33 | rational pair, so equal centers collapse and distinct centers never merge. |
| 34 | |
| 35 | 4. Completeness. A line meets a circle in at most two points, so any three of |
| 36 | the points on one circle are non-collinear and that circle is the |
| 37 | circumcircle of such a triple. Enumerating all non-collinear triples |
| 38 | therefore finds every circle through >= 3 points, each with at least 3 |
| 39 | points by construction. |
| 40 | |
| 41 | 5. Incidences. With canonical center (nx/m, ny/m) in the scaled plane, point |
| 42 | (Xi, Yi) lies on it iff (m*Xi - nx)^2 + (m*Yi - ny)^2 == (m*L)^2; this is |
| 43 | used to recount the points of every kept circle. |
| 44 | |
| 45 | Output center in the original plane: (nx/(m*L), ny/(m*L)), reduced. |
| 46 | """ |
| 47 | |
| 48 | import json |
| 49 | import sys |
| 50 | from functools import cmp_to_key |
| 51 | from math import gcd |
| 52 | |
| 53 | USAGE = "usage: python3 count.py <configuration.json>" |
| 54 | DIGITS = frozenset("0123456789") |
| 55 | |
| 56 | # Exactness-preserving pre-filter. The exact radius test of a triple is |
| 57 | # P^2 + Q^2 == 4 D^2 L^2; if it holds then it holds modulo every prime, so a |
| 58 | # triple whose congruence fails cannot be a unit circle and is dropped before |
| 59 | # the large multiplications. A triple that passes is still decided by the |
| 60 | # exact test, so the filter never changes an answer; it only avoids work with |
| 61 | # the very large integers a common denominator of big denominators produces. |
| 62 | FILTER_PRIMES = (1000000007, 998244353) |
| 63 | |
| 64 | |
| 65 | class Invalid(Exception): |
| 66 | """The configuration file is not a valid input.""" |
| 67 | |
| 68 | |
| 69 | def reduce_pair(num, den): |
| 70 | """Reduce num/den with den > 0 to lowest terms (gcd folded into the sign).""" |
| 71 | g = gcd(abs(num), den) |
| 72 | return (num // g, den // g) |
| 73 | |
| 74 | |
| 75 | def parse_coordinate(value, where): |
| 76 | """Return a reduced (numerator, denominator) with denominator > 0.""" |
| 77 | if isinstance(value, bool): |
| 78 | raise Invalid(where + ": boolean coordinate") |
| 79 | if isinstance(value, int): |
| 80 | return (value, 1) |
| 81 | if isinstance(value, float): |
| 82 | raise Invalid(where + ": floating-point coordinate; expected an" |
| 83 | " integer or a string \"p/q\"") |
| 84 | if not isinstance(value, str): |
| 85 | raise Invalid(where + ": coordinate must be an integer or a string" |
| 86 | " \"p/q\"") |
| 87 | body = value |
| 88 | sign = 1 |
| 89 | if body[:1] in ("+", "-"): |
| 90 | if body[0] == "-": |
| 91 | sign = -1 |
| 92 | body = body[1:] |
| 93 | slash = body.find("/") |
| 94 | if slash < 0: |
| 95 | raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) |
| 96 | num_text = body[:slash] |
| 97 | den_text = body[slash + 1:] |
| 98 | if not num_text or not den_text: |
| 99 | raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) |
| 100 | for text in (num_text, den_text): |
| 101 | for char in text: |
| 102 | if char not in DIGITS: |
| 103 | raise Invalid(where + ": %r is not a fraction \"p/q\"" |
| 104 | % (value,)) |
| 105 | den = int(den_text) |
| 106 | if den == 0: |
| 107 | raise Invalid(where + ": zero denominator") |
| 108 | return reduce_pair(sign * int(num_text), den) |
| 109 | |
| 110 | |
| 111 | def compare_centers(left, right): |
| 112 | """Order centers by exact rational (x, y); denominators are positive.""" |
| 113 | (lxn, lxd), (lyn, lyd) = left |
| 114 | (rxn, rxd), (ryn, ryd) = right |
| 115 | diff = lxn * rxd - rxn * lxd |
| 116 | if diff: |
| 117 | return -1 if diff < 0 else 1 |
| 118 | diff = lyn * ryd - ryn * lyd |
| 119 | if diff: |
| 120 | return -1 if diff < 0 else 1 |
| 121 | return 0 |
| 122 | |
| 123 | |
| 124 | def solve(points): |
| 125 | """points: [( (xn, xd), (yn, yd) ), ...] reduced. |
| 126 | |
| 127 | Return the centers of all distinct unit circles through >= 3 of the points, |
| 128 | as reduced ((xn, xd), (yn, yd)) pairs sorted by exact (x, y). |
| 129 | """ |
| 130 | n = len(points) |
| 131 | |
| 132 | # 1. Common denominator: point i is (xs[i]/scale, ys[i]/scale). |
| 133 | scale = 1 |
| 134 | for px, py in points: |
| 135 | for _, den in (px, py): |
| 136 | scale = scale // gcd(scale, den) * den |
| 137 | xs = [0] * n |
| 138 | ys = [0] * n |
| 139 | for i, (px, py) in enumerate(points): |
| 140 | xs[i] = px[0] * (scale // px[1]) |
| 141 | ys[i] = py[0] * (scale // py[1]) |
| 142 | |
| 143 | # 2./3. All non-collinear triples, radius test, canonical center. |
| 144 | four_l2 = 4 * scale * scale # (2 L)^2 |
| 145 | residues = [] |
| 146 | for prime in FILTER_PRIMES: |
| 147 | residues.append((prime, |
| 148 | [value % prime for value in xs], |
| 149 | [value % prime for value in ys], |
| 150 | scale % prime)) |
| 151 | circles = set() |
| 152 | for i in range(n - 2): |
| 153 | xi = xs[i] |
| 154 | yi = ys[i] |
| 155 | for j in range(i + 1, n - 1): |
| 156 | a = xs[j] - xi |
| 157 | b = ys[j] - yi |
| 158 | ab2 = a * a + b * b |
| 159 | for k in range(j + 1, n): |
| 160 | pass_filter = True |
| 161 | for prime, mod_x, mod_y, mod_l in residues: |
| 162 | fa = mod_x[j] - mod_x[i] |
| 163 | fb = mod_y[j] - mod_y[i] |
| 164 | fc = mod_x[k] - mod_x[i] |
| 165 | fd = mod_y[k] - mod_y[i] |
| 166 | fab = fa * fa + fb * fb |
| 167 | fcd = fc * fc + fd * fd |
| 168 | fdet = fa * fd - fb * fc |
| 169 | fp = fd * fab - fb * fcd |
| 170 | fq = fa * fcd - fc * fab |
| 171 | if (fp * fp + fq * fq |
| 172 | - 4 * fdet * fdet * mod_l * mod_l) % prime: |
| 173 | pass_filter = False |
| 174 | break |
| 175 | if not pass_filter: |
| 176 | continue |
| 177 | c = xs[k] - xi |
| 178 | d = ys[k] - yi |
| 179 | det = a * d - b * c |
| 180 | if det == 0: # collinear triple |
| 181 | continue |
| 182 | cd2 = c * c + d * d |
| 183 | px_off = d * ab2 - b * cd2 # P = Nx - 2 D Xi |
| 184 | py_off = a * cd2 - c * ab2 # Q = Ny - 2 D Yi |
| 185 | if px_off * px_off + py_off * py_off != four_l2 * det * det: |
| 186 | continue # circumradius != 1 |
| 187 | nx = 2 * det * xi + px_off |
| 188 | ny = 2 * det * yi + py_off |
| 189 | den = 2 * det |
| 190 | g = gcd(gcd(abs(nx), abs(ny)), abs(den)) |
| 191 | nx //= g |
| 192 | ny //= g |
| 193 | den //= g |
| 194 | if den < 0: |
| 195 | nx = -nx |
| 196 | ny = -ny |
| 197 | den = -den |
| 198 | circles.add((nx, ny, den)) |
| 199 | |
| 200 | # 5. Recount incidences exactly; the center in the original plane is |
| 201 | # (nx/(den*scale), ny/(den*scale)). |
| 202 | centers = [] |
| 203 | for nx, ny, den in circles: |
| 204 | den2_l2 = den * den * scale * scale |
| 205 | on_circle = 0 |
| 206 | for idx in range(n): |
| 207 | u = den * xs[idx] - nx |
| 208 | v = den * ys[idx] - ny |
| 209 | if u * u + v * v == den2_l2: |
| 210 | on_circle += 1 |
| 211 | if on_circle < 3: # impossible by construction; keeps count honest |
| 212 | continue |
| 213 | total = den * scale |
| 214 | centers.append((reduce_pair(nx, total), reduce_pair(ny, total))) |
| 215 | |
| 216 | centers.sort(key=cmp_to_key(compare_centers)) |
| 217 | return centers |
| 218 | |
| 219 | |
| 220 | def read_points(document): |
| 221 | """Validate the document; return (n, points) or raise Invalid.""" |
| 222 | if not isinstance(document, dict): |
| 223 | raise Invalid("the configuration must be a JSON object") |
| 224 | schema = document.get("schema") |
| 225 | if isinstance(schema, bool) or not isinstance(schema, int) or schema != 1: |
| 226 | raise Invalid("schema must be the integer 1") |
| 227 | raw_points = document.get("points") |
| 228 | if not isinstance(raw_points, list): |
| 229 | raise Invalid("points must be a list") |
| 230 | n = len(raw_points) |
| 231 | if n < 3 or n > 80: |
| 232 | raise Invalid("need 3 to 80 points, got %d" % n) |
| 233 | points = [] |
| 234 | seen = set() |
| 235 | for index, item in enumerate(raw_points): |
| 236 | if not isinstance(item, list) or len(item) != 2: |
| 237 | raise Invalid("point %d is not a pair [x, y]" % index) |
| 238 | px = parse_coordinate(item[0], "point %d x" % index) |
| 239 | py = parse_coordinate(item[1], "point %d y" % index) |
| 240 | if (px, py) in seen: |
| 241 | raise Invalid("point %d repeats an earlier point" % index) |
| 242 | seen.add((px, py)) |
| 243 | points.append((px, py)) |
| 244 | return n, points |
| 245 | |
| 246 | |
| 247 | def format_rational(pair): |
| 248 | num, den = pair |
| 249 | if den == 1: |
| 250 | return str(num) |
| 251 | return "%d/%d" % (num, den) |
| 252 | |
| 253 | |
| 254 | def main(argv): |
| 255 | if len(argv) != 2: |
| 256 | sys.stderr.write(USAGE + "\n") |
| 257 | return 1 |
| 258 | try: |
| 259 | with open(argv[1], "rb") as handle: |
| 260 | blob = handle.read() |
| 261 | except OSError as exc: |
| 262 | sys.stderr.write("cannot read %s: %s\n" % (argv[1], exc.strerror or exc)) |
| 263 | return 1 |
| 264 | try: |
| 265 | document = json.loads(blob) |
| 266 | except (ValueError, RecursionError) as exc: |
| 267 | sys.stderr.write("not valid JSON: %s\n" % (exc,)) |
| 268 | return 1 |
| 269 | try: |
| 270 | n, points = read_points(document) |
| 271 | except Invalid as exc: |
| 272 | sys.stderr.write("%s\n" % (exc,)) |
| 273 | return 1 |
| 274 | |
| 275 | centers = solve(points) |
| 276 | payload = { |
| 277 | "n": n, |
| 278 | "unit_circles": len(centers), |
| 279 | "centers": [[format_rational(cx), format_rational(cy)] |
| 280 | for cx, cy in centers], |
| 281 | } |
| 282 | sys.stdout.write(json.dumps(payload) + "\n") |
| 283 | return 0 |
| 284 | |
| 285 | |
| 286 | if __name__ == "__main__": |
| 287 | sys.exit(main(sys.argv)) |