"""Fixed-point interval check. Every endpoint represents an integer divided by Q."""
from math import isqrt
Q=10**9
class I:
    def __init__(self,l,h):self.l,self.h=l,h
    def __add__(x,y):return I(x.l+y.l,x.h+y.h)
    def __sub__(x,y):return I(x.l-y.h,x.h-y.l)
    def __mul__(x,y):
        v=[a*b for a in (x.l,x.h) for b in (y.l,y.h)]
        return I(min(v)//Q,-(-max(v)//Q))
    def __truediv__(x,y):
        assert y.l>0
        return x*I(Q*Q//y.h,-(-Q*Q//y.l))
    def square(x):
        return I(0 if x.l<=0<=x.h else min(x.l*x.l,x.h*x.h)//Q,-(-max(x.l*x.l,x.h*x.h)//Q))
    def sqrt(x):
        assert x.l>=0
        return I(isqrt(x.l*Q),1+isqrt(x.h*Q))
one=I(Q,Q);two=one+one
def step(t,w):
    A=one+two*t;B=two+t;d=one-t
    root=((one-A*w).square()+A*d*w.square()).sqrt()
    f=(one+root)/A;R=one+d*f
    return f/R, (B*w-one)*(one-d*w)/(root*R)
def box(k,m):
    return I(k*Q//m,-(-(k+1)*Q//m))
# Derivatives at fixed w of f, R and F=f/R, plus partials in w.
def calculus(t,w):
    A=one+two*t;B=two+t;d=one-t
    r=((one-A*w).square()+A*d*w.square()).sqrt()
    f=(one+r)/A;R=one+d*f
    fw=(B*w-one)/r
    # A f^2 - 2 f + 2w - B w^2 = 0
    ft=(w.square()-two*f.square())/(two*r)
    Rt=d*ft-f
    return R, f/R,(ft+f.square())/R.square(),fw/R.square(),Rt/R,d*fw/R

def uniform():
    low=Q;hi=-Q;lo2=Q;hi2=-Q;midlow=Q;midhigh=-Q
    bounds=[0]*4; Rmin=10*Q
    for i in range(250):
        t=box(i,500)
        for j in range(500):
            w=box(j,750);v,L=step(t,w)
            midlow=min(midlow,L.l);midhigh=max(midhigh,L.h)
            if i<160:
                z,M=step(t,v)
                low=min(low,L.l);hi=max(hi,L.h)
                lo2=min(lo2,M.l);hi2=max(hi2,M.h)
            if i<40:
                R,_,*D=calculus(t,w)
                Rmin=min(Rmin,R.l)
                bounds=[max(b,abs(x.l),abs(x.h)) for b,x in zip(bounds,D)]
    print('L ranges:',low,hi,lo2,hi2,midlow,midhigh)
    assert low>=-56*Q//100 and hi<=26*Q//100 and lo2>=0 and hi2<=30*Q//100
    assert midlow>=-68*Q//100 and midhigh<=43*Q//100
    print('small t: min R, max abs(Ft,Fw,(log R)t,(log R)w)',Rmin,*bounds)
    assert Rmin>=2*Q and all(b<=c for b,c in zip(bounds,[18*Q//100,15*Q//100,212*Q//100,36*Q//100]))
if __name__=='__main__':uniform()
def birth(m,t):
    # Start at width zero, so m genuine layers follow.
    w=I(0,0);H=t
    for _ in range(m):
        R,w,*_=calculus(t,w);H=H*R
    return H
if __name__=='__main__':
    floor=min(birth(3,box(i,1000)).l for i in range(80,320))
    print('H3 lower bound on [.08,.32]:',floor)
    assert floor>Q
    for m,k in [(2,319448),(3,63817),(4,18898),(5,6346)]:
        a=I(k*1000,k*1000);b=I(a.l+1000,a.h+1000)
        assert birth(m,a).h<Q<birth(m,b).l
        print('transition',m,'in millionths:',k,k+1)
