"""Verify the local gap-30 certificate at 43 by sieving ticks, independently of XII's prefix code."""
from math import gcd,prod,isqrt
import json


def experiment():
    primes = [p for p in range(2,44) if all(p%d for d in range(2,isqrt(p)+1))]
    period = prod(primes)
    anchor, address, gap = 4360920443890010,4360920492100729,30
    claimed_anchor_rank, target = 603296659486,603296665977
    # Include the right endpoint of every candidate gap, including the final candidate.
    length = address-anchor+gap+1
    surviving = bytearray([1])*length
    for p in primes:
        first = (-anchor)%p
        surviving[first::p] = bytes(len(range(first,length,p)))
    pattern = bytes([1])+bytes(gap-1)+bytes([1])
    offset = surviving.find(pattern)
    before = 0
    while 0 <= offset < address-anchor:
        before += 1
        offset = surviving.find(pattern,offset+1)
    assert offset == address-anchor and before == target-claimed_anchor_rank
    assert [x for x in range(gap+1) if gcd(address+x,period)==1] == [0,gap]
    return dict(period=period,anchor=anchor,address=address,gap=gap,earlier_starts=before,
                ticks_sieved=length,rank_if_anchor_is_correct=claimed_anchor_rank+before)


if __name__=="__main__":
    print(json.dumps(experiment(),indent=2))
