"""Numerical check for "Halving the even top elements of the Schinzel-Szekeres set".

For a given x it prints
  (1 - sum_{n in B(x)} 1/n) * log x       (should approach Weingartner's delta = 0.5604)
  N(x) * log x / x, where N(x) = #{m odd, x/6 < m <= x/4, F(m) <= x}   (predicted g0 = 0.0575)
  (sum_{c in E} 1/c) * log x, E = even elements of B(x) above 2x/3
and, for x <= 3000, the number of pairs in the halved set S with lcm <= x (should be 0).

F(n) = max_{d | n, d > 1} d * P^-(d) satisfies F(n) = max(F(n/p), p*n) with p = P^-(n):
divisors of n are divisors of n/p or p times them, and for d = p*d' we have P^-(d) = p, so d*P^-(d) <= p*n.
B(x) = {n <= x : F(n) > x and F(d) <= x for proper divisors d}; since F is monotone along divisibility,
it suffices to test the maximal proper divisors n/q, q | n prime.

Usage: python3 check.py <x>      (needs numpy)
"""
import math
import sys
from math import gcd

import numpy as np


def smallest_prime_factor_table(N):
    spf = np.zeros(N + 1, dtype=np.int64)
    for i in range(2, N + 1):
        if spf[i] == 0:
            block = spf[i::i]
            block[block == 0] = i
    return spf


def main():
    x = int(sys.argv[1]) if len(sys.argv) > 1 else 10**6
    spf = smallest_prime_factor_table(x)
    F = np.ones(x + 1, dtype=np.int64)
    for n in range(2, x + 1):
        p = int(spf[n])
        F[n] = max(int(F[n // p]), p * n)

    def prime_factors(n):
        out = set()
        while n > 1:
            p = int(spf[n])
            out.add(p)
            n //= p
        return out

    B = [n for n in range(2, x + 1) if F[n] > x and all(F[n // q] <= x for q in prime_factors(n))]
    E = [c for c in B if c % 2 == 0 and 3 * c > 2 * x]
    N = sum(1 for m in range(x // 6 + 1, x // 4 + 1) if m % 2 == 1 and F[m] <= x)
    L = math.log(x)
    sum_B = sum(1 / n for n in B)
    gain = sum(1 / c for c in E)
    print(f"x = {x}")
    print(f"|B(x)| = {len(B)}, (1 - sum_B 1/n) * log x = {(1 - sum_B) * L:.4f}")
    print(f"N(x) = {N}, N(x) * log x / x = {N * L / x:.4f}")
    print(f"|E| = {len(E)}, (sum_E 1/c) * log x = {gain * L:.4f}, sum over S = {sum_B + gain:.6f}")
    if x <= 3000:
        Eset = set(E)
        S = sorted([n for n in B if n not in Eset] + [c // 2 for c in E])
        bad = sum(1 for i, a in enumerate(S) for b in S[i + 1:] if a * b // gcd(a, b) <= x)
        print(f"|S| = {len(S)}, pairs in S with lcm <= x: {bad}")


if __name__ == "__main__":
    main()
