#!/usr/bin/env python3 """Exact counter for unit circles through at least three of n rational points. Usage: python3 count.py Method (pair-based chord construction, O(n^2) candidate pairs). For an unordered pair of points p1, p2 with squared distance d2 (0 < d2 <= 4), the centres of the two unit circles through the pair are c = m +/- (k/2) * perp(p2 - p1), perp(dx, dy) = (-dy, dx), m = (p1 + p2)/2, k = sqrt((4 - d2) / d2). Only pairs whose k is rational can yield a rational centre, and every centre of a unit circle through three rational points is rational: three non-collinear rational points have a rational circumcentre (a nonsingular linear system with rational coefficients), and three distinct collinear points lie on no circle. So enumerating rational candidates over all pairs loses no circle. All arithmetic is exact. Coordinates are fractions.Fraction throughout; the input coordinates are scaled once by a common integer to make every point integral, so candidate generation and the final "exactly three points at distance 1" test are pure integer arithmetic. No floating point value is ever created: k rational is decided by reducing (4-d2)/d2 and testing that numerator and denominator are perfect squares (math.isqrt), never by a float square root. """ import json import math import re import sys from fractions import Fraction # Python 3.11+ refuses int() on strings longer than 4300 digits by default. # A coordinate may legitimately be a huge exact integer or fraction; the # exactness of the count must not depend on that interpreter guard. if hasattr(sys, "set_int_max_str_digits"): sys.set_int_max_str_digits(0) class Invalid(Exception): """The configuration does not satisfy the input contract.""" # "p/q" exactly: an optionally negative integer over a non-negative integer. # No sign on the denominator (q must be positive), no whitespace, no decimal # point, no exponent, no other characters. _FRACTION_RE = re.compile(r"\A(-?[0-9]+)/([0-9]+)\Z") def _coordinate(value, where): """Parse one coordinate; raise Invalid unless it is an integer or 'p/q'.""" if isinstance(value, bool): raise Invalid(f"{where} is a JSON boolean, not a number") if isinstance(value, float): raise Invalid(f"{where} is a JSON float, not an integer or fraction") if isinstance(value, int): return Fraction(value) if isinstance(value, str): match = _FRACTION_RE.match(value) if match is None: raise Invalid(f"{where} {value!r} is not exactly a fraction p/q") numerator = int(match.group(1)) denominator = int(match.group(2)) if denominator == 0: raise Invalid(f"{where} {value!r} has a zero denominator") return Fraction(numerator, denominator) raise Invalid(f"{where} is not an integer or a 'p/q' string") def load_configuration(path): """Read and validate the configuration file; return the points.""" try: with open(path, "r", encoding="utf-8-sig") as handle: document = json.load(handle) except OSError as exc: raise Invalid(f"cannot read {path}: {exc.strerror or exc}") except UnicodeDecodeError: raise Invalid(f"{path} is not valid UTF-8") except RecursionError: raise Invalid(f"{path} is nested too deeply to be a configuration") except json.JSONDecodeError as exc: raise Invalid(f"{path} is not valid JSON: {exc.msg} at line {exc.lineno}") if not isinstance(document, dict): raise Invalid("the top-level JSON value must be an 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 an array') count = len(raw_points) if not 3 <= count <= 80: raise Invalid(f"need 3 <= n <= 80 points, got {count}") points = [] for index, raw_point in enumerate(raw_points): if not isinstance(raw_point, list) or len(raw_point) != 2: raise Invalid(f"point {index} must be an array of exactly two coordinates") x = _coordinate(raw_point[0], f"point {index} x") y = _coordinate(raw_point[1], f"point {index} y") points.append((x, y)) seen = set() for index, point in enumerate(points): if point in seen: raise Invalid(f"point {index} duplicates an earlier point after reduction") seen.add(point) return points def _rational_sqrt_ratio(numerator, denominator): """Return (a, b) with a/b == sqrt(numerator/denominator), or None. numerator and denominator are positive integers, not necessarily coprime. The ratio is the square of a rational exactly when, after reduction, both parts are perfect squares of integers; that is decided with math.isqrt. """ common = math.gcd(numerator, denominator) numerator //= common denominator //= common root_num = math.isqrt(numerator) root_den = math.isqrt(denominator) if root_num * root_num != numerator or root_den * root_den != denominator: return None return root_num, root_den def count_unit_circles(points): """Return [(cx, cy, [point indices on the circle]), ...] sorted by (cx, cy). Every returned circle has radius exactly 1 and at least three input points at distance exactly 1 from its centre. """ n = len(points) # One common denominator: with scale = lcm of all coordinate denominators, # every point is (xs[i]/scale, ys[i]/scale) with xs[i], ys[i] integers. scale = 1 for x, y in points: scale = scale * x.denominator // math.gcd(scale, x.denominator) scale = scale * y.denominator // math.gcd(scale, y.denominator) xs = [int(x * scale) for x, _ in points] ys = [int(y * scale) for _, y in points] four_scale_sq = 4 * scale * scale # Candidate centres from every pair at distance at most 2. candidates = set() for i in range(n): x1, y1 = xs[i], ys[i] for j in range(i + 1, n): x2, y2 = xs[j], ys[j] dx = x2 - x1 dy = y2 - y1 d2 = dx * dx + dy * dy # (distance * scale)^2 if d2 == 0 or d2 > four_scale_sq: # d2 = 0 only for a repeated point, which validation rejects; # d2 > 4 puts the pair outside every unit circle. continue sum_x = x1 + x2 sum_y = y1 + y2 if d2 == four_scale_sq: # Chord of length exactly 2: the centre is the midpoint. candidates.add((Fraction(sum_x, 2 * scale), Fraction(sum_y, 2 * scale))) continue root = _rational_sqrt_ratio(four_scale_sq - d2, d2) if root is None: # k is irrational, so this pair lies on no unit circle with a # rational centre, and every circle we must count has one. continue a, b = root # k = sqrt((4-d2)/d2) = a/b denominator = 2 * scale * b # centre = ((x1+x2) -/+ k*dy, (y1+y2) +/- k*dx) / (2*scale) candidates.add( ( Fraction(sum_x * b - a * dy, denominator), Fraction(sum_y * b + a * dx, denominator), ) ) candidates.add( ( Fraction(sum_x * b + a * dy, denominator), Fraction(sum_y * b - a * dx, denominator), ) ) # Keep the candidates with at least three points at distance exactly 1. centres = [] for cx, cy in candidates: centre_den = cx.denominator * cy.denominator // math.gcd(cx.denominator, cy.denominator) ax = int(cx * centre_den) # centre = (ax/centre_den, ay/centre_den) ay = int(cy * centre_den) target = (scale * centre_den) ** 2 on_circle = [] for i in range(n): ux = xs[i] * centre_den - ax * scale uy = ys[i] * centre_den - ay * scale if ux * ux + uy * uy == target: on_circle.append(i) if len(on_circle) >= 3: centres.append((cx, cy, on_circle)) centres.sort(key=lambda item: (item[0], item[1])) return centres def format_rational(value): """Reduced string: 'a' when integral, else 'p/q' with q > 1 and gcd = 1.""" # Fraction is always normalised: gcd(|p|, q) = 1 and q > 0. return str(value) def main(argv): if len(argv) != 2: print("usage: python3 count.py ", file=sys.stderr) return 1 try: points = load_configuration(argv[1]) except Invalid as exc: print(f"invalid configuration: {exc}", file=sys.stderr) return 1 centres = count_unit_circles(points) payload = { "n": len(points), "unit_circles": len(centres), "centers": [[format_rational(cx), format_rational(cy)] for cx, cy, _ in centres], } sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))