"""Check circle counts for the regular polygon construction by exact modular reduction.

Usage: python3 erdos506_spectrum.py [n ...]. Uses only the standard library.
The reduction maps roots of unity and their inverses into a prime field. Distinct
ordinary circles from noncollinear triples in the reduction certify distinct
ordinary circles over C at the chosen real configuration.
"""
from itertools import combinations
from math import comb, gcd, isqrt
import sys


def prime_factors(number):
    factors = []
    for d in range(2, isqrt(number) + 1):
        if number % d == 0:
            factors.append(d)
            while number % d == 0:
                number //= d
    if number > 1:
        factors.append(number)
    return factors


def reduction(k):
    order = 2 * k
    multiple = 10**6 // order + 1
    while True:
        p = multiple * order + 1
        if all(p % d for d in range(2, isqrt(p) + 1)):
            break
        multiple += 1
    for a in range(2, p):
        root = pow(a, (p-1)//order, p)
        if all(pow(root, order//d, p) != 1 for d in prime_factors(order)):
            return p, root
    raise ArithmeticError('root of unity unavailable')


def certificate(n):
    k = n-2
    p, root = reduction(k)
    def point(radius, angle):
        return radius*pow(root, angle % (2*k), p) % p, radius*pow(root, -angle % (2*k), p) % p
    verts = [point(1, 2*j) for j in range(k)]
    A, B, C = [point(2, a) for a in (1, 5, 9)]
    def image(pt):
        return (pow((pt[0]-A[0]) % p, -1, p), pow((pt[1]-A[1]) % p, -1, p))
    pts = [image(v) for v in verts + [B, C]]
    assert len(set(pts)) == n
    # A normalized ordinary circle has zw + a*z + b*w + c = 0, where w represents conjugate(z).
    data = [(z, w, z*w % p) for z, w in pts]
    circles = set()
    for (x,y,f),(u,v,g),(h,j,s) in combinations(data, 3):
        uz, vw, hz, jw = u-x, v-y, h-x, j-y
        det = (uz*jw-vw*hz) % p
        if det == 0:
            continue
        inv = pow(det, -1, p)
        a = ((f-g)*jw-vw*(f-s))*inv % p
        b = (uz*(f-s)-(f-g)*hz)*inv % p
        circles.add((a,b,(-f-a*x-b*y) % p))
    expected = 1 + 2*comb(k,2) - 3*(k//2) + k%2
    assert len(circles) == expected, (n, p, len(circles), expected)
    last = 1 + comb(n-1,2)
    print(f'n={n} prime={p} root={root} first_band=[{last-(n-1)//2},{last}] next={len(circles)} missing={len(circles)-last-1}')


def determinant(a, b, c):
    return (a[0]*(b[1]*c[2]-b[2]*c[1]) - a[1]*(b[0]*c[2]-b[2]*c[0])
            + a[2]*(b[0]*c[1]-b[1]*c[0]))


def general_position_certificate(n):
    """Use integer homogeneous coordinates, testing every attainable count of the second band."""
    k = n-2
    for pairs in range(k//2+1):
        parameters = list(range(2, 2+k-pairs)) + list(range(-2, -2-pairs, -1))
        points = [(1-z*z, 2*z, 1+z*z) for z in parameters] + [(0,2,1), (0,-2,1)]
        # A pole traversing this parabola eventually avoids the finitely many bad circles and lines.
        for m in range(1, 200):
            rows = []
            for x,y,w in points:
                dx,dy = x-m*w, y-(m*m+7)*w
                u,v,h = dx*w, -dy*w, dx*dx+dy*dy
                rows.append((u*u+v*v, u*h, v*h, h*h))
            circles = set()
            for a,b,c in combinations(rows, 3):
                leading = determinant(a[1:], b[1:], c[1:])
                if not leading:
                    break
                coefficients = [leading]
                for j in (1,2,3):
                    minor = determinant(*(r[:j]+r[j+1:] for r in (a,b,c)))
                    coefficients.append((-1)**j*minor)
                divisor = gcd(*coefficients)*(1 if leading>0 else -1)
                circles.add(tuple(v//divisor for v in coefficients))
            else:
                assert len(circles) == k*k+1-3*pairs
                break
        else:
            raise AssertionError('No suitable pole found in sampled range')
    print(f'n={n} no three collinear: verified all {k//2+1} counts from {k*k+1-3*(k//2)} to {k*k+1} in steps of three')


if __name__ == '__main__':
    if sys.argv[1:2] == ['--general-position']:
        for n_text in sys.argv[2:] or ('35', '36'):
            general_position_certificate(int(n_text))
    else:
        for n_text in sys.argv[1:] or ('32', '33', '64', '65'):
            certificate(int(n_text))
