"""Finite check of the unitary factorization used for Erdős problem 824.

Usage: python3 erdos824_primitive.py [exclusive upper bound, default 1000].
"""
from collections import defaultdict
from functools import cache
from itertools import combinations
from math import gcd
import sys


def check(limit):
    divisors = [[] for _ in range(limit)]
    for d in range(1, limit):
        for n in range(d, limit, d):
            divisors[n].append(d)
    sigma = [sum(ds) for ds in divisors]
    fibers = defaultdict(list)
    for n in range(2, limit):
        fibers[sigma[n]].append(n)
    pairs = {
        (a, b) for fiber in fibers.values() for a, b in combinations(fiber, 2)
        if gcd(a, b) == 1
    }
    unitary = {
        n: {sigma[d] for d in divisors[n] if 1 < d < n and gcd(d, n // d) == 1}
        for n in range(2, limit)
    }
    atoms = {(a, b) for a, b in pairs if unitary[a].isdisjoint(unitary[b])}
    oriented = {(a, b) for a, b in pairs} | {(b, a) for a, b in pairs}
    composite = set()
    for a, b in pairs:
        for c, d in oriented:
            ac, bd = a * c, b * d
            if max(ac, bd) < limit and gcd(a, c) == gcd(b, d) == gcd(ac, bd) == 1:
                composite.add(tuple(sorted((ac, bd))))
    assert composite == pairs - atoms

    @cache
    def squarefree(n):
        return all(d == 1 or n % (d * d) != 0 for d in divisors[n])

    def both_squarefree(pair):
        return all(squarefree(n) for n in pair)

    print(f"max(a,b) < {limit}: {len(pairs)} coprime pairs, {len(atoms)} primitive")
    print(f"both squarefree: {sum(map(both_squarefree, pairs))} pairs, "
          f"{sum(map(both_squarefree, atoms))} primitive")
    if composite:
        print("first composite by larger member:", min(composite, key=lambda p: (p[1], p[0])))


if __name__ == "__main__":
    check(int(sys.argv[1]) if len(sys.argv) > 1 else 1000)
