"""Shared interval sieve from a certified anchor p_k. Counts repeats of candidate tests."""
from math import gcd,isqrt
import json


def primes_to(n):
    keep=bytearray([1])*(n+1)
    keep[:2]=b'\x00\x00'
    for p in range(2,isqrt(n)+1):
        if keep[p]:
            keep[p*p::p]=bytes((n-p*p)//p+1)
    return [i for i,v in enumerate(keep) if v]


def run(k,batch):
    if k not in (100,1000,4000) or not 1<=batch<=64:
        raise ValueError("unsupported anchor or length")
    anchor={100:541,1000:7919,4000:37813}[k]
    end=anchor+32*batch
    while True:
        least={}
        for p in primes_to(isqrt(end)):
            for m in range(max(p*p,((anchor+1+p-1)//p)*p),end+1,p):
                least.setdefault(m,p)
        answers=[]; rejected=[]; checks=0; separate=0
        for x in range(anchor+1,end+1):
            if gcd(210,x)!=1:
                continue
            checks+=1
            if x in least:
                rejected.append([x,least[x]])
            else:
                answers.append(x)
                separate+=checks
                if len(answers)==batch:
                    witness=primes_to(x)
                    assert len(witness)==k+batch and witness[k-1:k+batch]==[anchor]+answers
                    assert all(x%p==0 and all(x%d for d in range(2,p)) for x,p in rejected)
                    return dict(anchor=anchor,primes=answers,rejected=rejected,checks=checks,separate=separate,
                                sieve_end=end,marked=len(least))
        end+=end-anchor


if __name__=='__main__':
    print(json.dumps([dict(k=k,batch=b,**run(k,b)) for k in (100,1000,4000) for b in (1,8,32,64)],indent=2))
