"""Weingartner's constants a_{y,2} by his formula (23) and Section 7.2.

  a_{y,z} = C Pi(z) (1 - gamma + log y - Sigma(z)) + C (J(N) + Q(N)),   C = 1/(1 - e^{-gamma}),
  J(N)   = int_1^N A(t,y,z) g(yt) dt/t^2,   g(u) = (Sigma(u) + gamma - log u) Pi(u),
  eps(N) = Pi(z) - int_1^N A(t,y,z) Pi(yt) dt/t^2,   |Q(N)| <= E(yN) eps(N),
  E(x)   = sup_{t >= x} |Sigma(t) + gamma - log t|,  Sigma(t) = sum_{p<=t} log p/(p-1), Pi(t) = prod_{p<=t}(1-1/p).

Here z = 2, so A(t,y,2) counts odd n <= t with F(n) <= t y (n = 1 included, F(1) = 1).
An odd n is counted for t >= thr(n) = max(n, F(n)/y), so
  J(N) = sum_{odd n, thr(n) < N} y (K(yN) - K(y thr(n))),   K(U) = int_1^U g(u)/u^2 du,
and similarly for eps(N) with P(U) = int_1^U Pi(u)/u^2 du. K and P are piecewise closed forms between primes.

Usage: python3 ay2.py <Umax> y1 y2 ...      (N = Umax / y for each y; prints a_{y,2}, J, eps, |Q| bound factor)
"""
import math
import sys

import numpy as np

LD = np.longdouble                      # x87 extended precision (64-bit mantissa, eps = 1.08e-19)
GAMMA = LD("0.57721566490153286060651209")
C = LD(1) / (LD(1) - np.exp(-GAMMA))


def primes_upto(U):
    s = np.ones(U + 1, dtype=bool)
    s[:2] = False
    for i in range(2, int(U ** 0.5) + 1):
        if s[i]:
            s[i * i::i] = False
    return np.nonzero(s)[0]


def F_table(N, primes):
    """F(n) for n <= N (int64), F(1) = 1, F(0) unused. F(n) = max(F(n/p), p n), p = P^-(n)."""
    spf = np.zeros(N + 1, dtype=np.int64)
    for p in primes[primes <= int(N ** 0.5) + 1]:
        blk = spf[p * p::p]
        blk[blk == 0] = p
    idx = np.arange(N + 1, dtype=np.int64)
    spf[spf == 0] = idx[spf == 0]          # primes (and 0, 1)
    # Omega(n) by repeated division
    omega = np.zeros(N + 1, dtype=np.int16)
    m = idx.copy()
    while True:
        act = m > 1
        if not act.any():
            break
        omega[act] += 1
        m[act] //= spf[m[act]]
    F = np.ones(N + 1, dtype=np.int64)
    for k in range(1, int(omega.max()) + 1):
        n = np.nonzero(omega == k)[0]
        p = spf[n]
        F[n] = np.maximum(F[n // p], p * n)
    return F


class Cumul:
    """K(U) = int_1^U g(u)/u^2 du and P(U) = int_1^U Pi(u)/u^2 du, piecewise between primes."""

    def __init__(self, primes):
        p = primes.astype(LD)
        logp = np.log(p)
        Sig = np.cumsum(logp / (p - 1.0))            # Sigma at p_i (inclusive)
        Pi = np.exp(np.cumsum(np.log1p(-1.0 / p)))   # Pi at p_i (inclusive)
        # breakpoints b_0 = 1, b_i = p_{i-1}; on [b_i, b_{i+1}) Sigma = S_i, Pi = P_i
        self.b = np.concatenate(([LD(1)], p))
        self.S = np.concatenate(([LD(0)], Sig))
        self.P = np.concatenate(([LD(1)], Pi))
        a, bb = self.b[:-1], self.b[1:]
        segK = self.P[:-1] * ((self.S[:-1] + GAMMA) * self._inv(a, bb) - self._ilog(a, bb))
        segP = self.P[:-1] * self._inv(a, bb)
        self.nseg = len(segK)
        self.sabsK = float(np.sum(np.abs(segK)))      # for the rounding bound of the cumulative sums
        self.sabsP = float(np.sum(np.abs(segP)))
        self.cK = np.concatenate(([LD(0)], np.cumsum(segK)))
        self.cP = np.concatenate(([LD(0)], np.cumsum(segP)))

    @staticmethod
    def _inv(a, b):  # 1/a - 1/b without cancellation
        return (b - a) / (a * b)

    @classmethod
    def _ilog(cls, a, b):  # int_a^b log u / u^2 du = (log a + 1)(1/a - 1/b) - log(b/a)/b
        return (np.log(a) + 1) * cls._inv(a, b) - np.log1p((b - a) / a) / b

    def KP(self, U):
        U = np.asarray(U, dtype=LD)
        i = np.searchsorted(self.b, U, side="right") - 1
        a = self.b[i]
        K = self.cK[i] + self.P[i] * ((self.S[i] + GAMMA) * self._inv(a, U) - self._ilog(a, U))
        P = self.cP[i] + self.P[i] * self._inv(a, U)
        return K, P


UNIT = float(np.finfo(LD).eps) / 2        # unit roundoff of long double


def rounding_bound(y, M, cum):
    """Worst-case rounding error of J and eps (Higham: a recursive sum of n terms errs by <= (n-1) u sum|x_i|).
    Each cumulative value cK[i], cP[i] errs by <= nseg*u*sabs (+ the inputs S, Pi, which carry relative
    errors <= nseg*u*20 and enter K, P with weights <= sabs); each evaluation K(U) adds <= 20 u * 1.
    J = y * sum of M differences K(yN) - K(y thr); the final sum adds log2(M) u sum|terms|."""
    per = 2 * (cum.nseg * UNIT * (cum.sabsK + 20 * cum.sabsK) + 20 * UNIT)
    perP = 2 * (cum.nseg * UNIT * (cum.sabsP + 20 * cum.sabsP) + 20 * UNIT)
    J = y * M * per * (1 + math.log2(max(M, 2)) * UNIT)
    E = y * M * perP * (1 + math.log2(max(M, 2)) * UNIT)
    return J, E


def a_y2(y, N, F, cum):
    n = np.arange(1, N + 1, 2, dtype=np.int64)
    yL = LD(y)
    thr = np.maximum(n.astype(LD), F[n].astype(LD) / yL)
    thr = thr[thr < N]
    KN, PN = cum.KP(yL * N)
    Kt, Pt = cum.KP(yL * thr)
    J = yL * np.sum(KN - Kt)
    eps = LD("0.5") - yL * np.sum(PN - Pt)
    main = C * LD("0.5") * (1 - GAMMA + np.log(yL) - np.log(LD(2)))
    M = len(thr)
    return float(main + C * J), float(J), float(eps), M


def main():
    Umax = int(float(sys.argv[1]))
    ys = [float(v) for v in sys.argv[2:]]
    primes = primes_upto(Umax + 1)
    cum = Cumul(primes)
    Nmax = int(Umax / min(ys))
    F = F_table(Nmax, primes)
    for y in ys:
        N = int(Umax / y)
        a, J, eps, M = a_y2(y, N, F, cum)
        print(f"y={y:g} N={N} a_y2={a:.9f} J={J:.9f} eps={eps:.9f} C*eps={float(C) * eps:.6f}  (|error| <= C*eps*E(yN))")


if __name__ == "__main__":
    main()
