#!/usr/bin/env python3 """Count distinct circles of radius exactly 1 through >= 3 of n rational points. Usage: python3 count.py Exact integer arithmetic only: no floats, no fractions.Fraction, no square roots taken as values -- square roots appear only as perfect-square tests. Derivation used --------------- 1. Common scale. Let L be the lcm of the denominators of every coordinate, so point i is the integer pair (Xi, Yi) meaning (Xi/L, Yi/L). In the scaled plane the unit circle has radius exactly L and every comparison is integral. 2. Circumcenter. For a non-collinear triple take u = (a, b) = Pj - Pi, v = (c, d) = Pk - Pi and D = ad - bc != 0. "C is equidistant from Pi, Pj" is the linear equation 2 u.(C - Pi) = |u|^2, likewise for v; Cramer's rule on the two equations gives C = (Xi + P/(2D), Yi + Q/(2D)), P = d(a^2 + b^2) - b(c^2 + d^2), Q = a(c^2 + d^2) - c(a^2 + b^2). The squared distance to Pi is then (P^2 + Q^2)/(4 D^2), so the circle has radius 1 in the original plane iff its scaled radius is L, iff P^2 + Q^2 == 4 D^2 L^2. (no sqrt) That identity is necessary and sufficient; it is preceded by the same congruence modulo two primes, which is only necessary, so the pre-filter can drop a triple only when the exact test would reject it too. It exists because the common denominator of many large denominators can make every integer thousands of digits long even though no circle is ever found. 3. Dedup. The center is stored as the canonical integer triple (Nx, Ny, 2D) reduced by g = gcd(|Nx|, |Ny|, |2D|) with positive third entry, Nx = 2D*Xi + P, Ny = 2D*Yi + Q. A canonical triple is unique for a rational pair, so equal centers collapse and distinct centers never merge. 4. Completeness. A line meets a circle in at most two points, so any three of the points on one circle are non-collinear and that circle is the circumcircle of such a triple. Enumerating all non-collinear triples therefore finds every circle through >= 3 points, each with at least 3 points by construction. 5. Incidences. With canonical center (nx/m, ny/m) in the scaled plane, point (Xi, Yi) lies on it iff (m*Xi - nx)^2 + (m*Yi - ny)^2 == (m*L)^2; this is used to recount the points of every kept circle. Output center in the original plane: (nx/(m*L), ny/(m*L)), reduced. """ import json import sys from functools import cmp_to_key from math import gcd USAGE = "usage: python3 count.py " DIGITS = frozenset("0123456789") # Exactness-preserving pre-filter. The exact radius test of a triple is # P^2 + Q^2 == 4 D^2 L^2; if it holds then it holds modulo every prime, so a # triple whose congruence fails cannot be a unit circle and is dropped before # the large multiplications. A triple that passes is still decided by the # exact test, so the filter never changes an answer; it only avoids work with # the very large integers a common denominator of big denominators produces. FILTER_PRIMES = (1000000007, 998244353) class Invalid(Exception): """The configuration file is not a valid input.""" def reduce_pair(num, den): """Reduce num/den with den > 0 to lowest terms (gcd folded into the sign).""" g = gcd(abs(num), den) return (num // g, den // g) def parse_coordinate(value, where): """Return a reduced (numerator, denominator) with denominator > 0.""" if isinstance(value, bool): raise Invalid(where + ": boolean coordinate") if isinstance(value, int): return (value, 1) if isinstance(value, float): raise Invalid(where + ": floating-point coordinate; expected an" " integer or a string \"p/q\"") if not isinstance(value, str): raise Invalid(where + ": coordinate must be an integer or a string" " \"p/q\"") body = value sign = 1 if body[:1] in ("+", "-"): if body[0] == "-": sign = -1 body = body[1:] slash = body.find("/") if slash < 0: raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) num_text = body[:slash] den_text = body[slash + 1:] if not num_text or not den_text: raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) for text in (num_text, den_text): for char in text: if char not in DIGITS: raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) den = int(den_text) if den == 0: raise Invalid(where + ": zero denominator") return reduce_pair(sign * int(num_text), den) def compare_centers(left, right): """Order centers by exact rational (x, y); denominators are positive.""" (lxn, lxd), (lyn, lyd) = left (rxn, rxd), (ryn, ryd) = right diff = lxn * rxd - rxn * lxd if diff: return -1 if diff < 0 else 1 diff = lyn * ryd - ryn * lyd if diff: return -1 if diff < 0 else 1 return 0 def solve(points): """points: [( (xn, xd), (yn, yd) ), ...] reduced. Return the centers of all distinct unit circles through >= 3 of the points, as reduced ((xn, xd), (yn, yd)) pairs sorted by exact (x, y). """ n = len(points) # 1. Common denominator: point i is (xs[i]/scale, ys[i]/scale). scale = 1 for px, py in points: for _, den in (px, py): scale = scale // gcd(scale, den) * den xs = [0] * n ys = [0] * n for i, (px, py) in enumerate(points): xs[i] = px[0] * (scale // px[1]) ys[i] = py[0] * (scale // py[1]) # 2./3. All non-collinear triples, radius test, canonical center. four_l2 = 4 * scale * scale # (2 L)^2 residues = [] for prime in FILTER_PRIMES: residues.append((prime, [value % prime for value in xs], [value % prime for value in ys], scale % prime)) circles = set() for i in range(n - 2): xi = xs[i] yi = ys[i] for j in range(i + 1, n - 1): a = xs[j] - xi b = ys[j] - yi ab2 = a * a + b * b for k in range(j + 1, n): pass_filter = True for prime, mod_x, mod_y, mod_l in residues: fa = mod_x[j] - mod_x[i] fb = mod_y[j] - mod_y[i] fc = mod_x[k] - mod_x[i] fd = mod_y[k] - mod_y[i] fab = fa * fa + fb * fb fcd = fc * fc + fd * fd fdet = fa * fd - fb * fc fp = fd * fab - fb * fcd fq = fa * fcd - fc * fab if (fp * fp + fq * fq - 4 * fdet * fdet * mod_l * mod_l) % prime: pass_filter = False break if not pass_filter: continue c = xs[k] - xi d = ys[k] - yi det = a * d - b * c if det == 0: # collinear triple continue cd2 = c * c + d * d px_off = d * ab2 - b * cd2 # P = Nx - 2 D Xi py_off = a * cd2 - c * ab2 # Q = Ny - 2 D Yi if px_off * px_off + py_off * py_off != four_l2 * det * det: continue # circumradius != 1 nx = 2 * det * xi + px_off ny = 2 * det * yi + py_off den = 2 * det g = gcd(gcd(abs(nx), abs(ny)), abs(den)) nx //= g ny //= g den //= g if den < 0: nx = -nx ny = -ny den = -den circles.add((nx, ny, den)) # 5. Recount incidences exactly; the center in the original plane is # (nx/(den*scale), ny/(den*scale)). centers = [] for nx, ny, den in circles: den2_l2 = den * den * scale * scale on_circle = 0 for idx in range(n): u = den * xs[idx] - nx v = den * ys[idx] - ny if u * u + v * v == den2_l2: on_circle += 1 if on_circle < 3: # impossible by construction; keeps count honest continue total = den * scale centers.append((reduce_pair(nx, total), reduce_pair(ny, total))) centers.sort(key=cmp_to_key(compare_centers)) return centers def read_points(document): """Validate the document; return (n, points) or raise Invalid.""" if not isinstance(document, dict): raise Invalid("the configuration must be a JSON object") schema = document.get("schema") if isinstance(schema, bool) or not isinstance(schema, int) or schema != 1: raise Invalid("schema must be the integer 1") raw_points = document.get("points") if not isinstance(raw_points, list): raise Invalid("points must be a list") n = len(raw_points) if n < 3 or n > 80: raise Invalid("need 3 to 80 points, got %d" % n) points = [] seen = set() for index, item in enumerate(raw_points): if not isinstance(item, list) or len(item) != 2: raise Invalid("point %d is not a pair [x, y]" % index) px = parse_coordinate(item[0], "point %d x" % index) py = parse_coordinate(item[1], "point %d y" % index) if (px, py) in seen: raise Invalid("point %d repeats an earlier point" % index) seen.add((px, py)) points.append((px, py)) return n, points def format_rational(pair): num, den = pair if den == 1: return str(num) return "%d/%d" % (num, den) def main(argv): if len(argv) != 2: sys.stderr.write(USAGE + "\n") return 1 try: with open(argv[1], "rb") as handle: blob = handle.read() except OSError as exc: sys.stderr.write("cannot read %s: %s\n" % (argv[1], exc.strerror or exc)) return 1 try: document = json.loads(blob) except (ValueError, RecursionError) as exc: sys.stderr.write("not valid JSON: %s\n" % (exc,)) return 1 try: n, points = read_points(document) except Invalid as exc: sys.stderr.write("%s\n" % (exc,)) return 1 centers = solve(points) payload = { "n": n, "unit_circles": len(centers), "centers": [[format_rational(cx), format_rational(cy)] for cx, cy in centers], } sys.stdout.write(json.dumps(payload) + "\n") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))