"""Exploration: exact optimum (MILP, 1 excluded) vs the halved set S at the same x."""
import sys, math
from fractions import Fraction as Fr
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
from scipy.sparse import lil_matrix
x = int(sys.argv[1])
A = lil_matrix((x, x - 1))
for a in range(2, x + 1):
    for m in range(a, x + 1, a):
        A[m - 1, a - 2] = 1
c = -np.array([1 / a for a in range(2, x + 1)])
res = milp(c, constraints=LinearConstraint(A.tocsr(), -np.inf, 1), integrality=np.ones(x - 1), bounds=Bounds(0, 1),
           options={"mip_rel_gap": 0, "time_limit": 900})
O = {a for a in range(2, x + 1) if res.x[a - 2] > 0.5}
spf = list(range(x + 1))
for i in range(2, int(x ** 0.5) + 1):
    if spf[i] == i:
        for j in range(i * i, x + 1, i):
            if spf[j] == j: spf[j] = i
F = [1] * (x + 1)
for n in range(2, x + 1):
    p = spf[n]; F[n] = max(F[n // p], p * n)
def pf(n):
    s = set()
    while n > 1: s.add(spf[n]); n //= spf[n]
    return s
B = [n for n in range(2, x + 1) if F[n] > x and all(F[n // q] <= x for q in pf(n))]
E = {c for c in B if c % 2 == 0 and 3 * c > 2 * x}
S = set(b for b in B if b not in E) | {c // 2 for c in E}
L = math.log(x)
so, ss = float(sum(Fr(1, a) for a in O)), sum(1 / a for a in S)
print(f"x={x} status {res.status}: optimum {so:.6f} (1-R)log x={(1-so)*L:.4f}; halved S {ss:.6f} ({(1-ss)*L:.4f})")
onlyO, onlyS = sorted(O - S), sorted(S - O)
print(f"|O|={len(O)} |S|={len(S)} common {len(O & S)}")
print("in O not S:", onlyO[:60], '...' if len(onlyO) > 60 else '')
print("in S not O:", onlyS[:60], '...' if len(onlyS) > 60 else '')
print(f"sum over O-S {sum(1/a for a in onlyO):.5f}, over S-O {sum(1/a for a in onlyS):.5f}")
