#!/usr/bin/env python3
import sys, random, time, math
N=int(sys.argv[1]); seed=int(sys.argv[2]) if len(sys.argv)>2 else 1; random.seed(seed)
x=[0]*(N+1)
def mu(n):
    if n%3==1: return 1
    if n%3==2: return -1
    return -mu(n//3)
for i in range(1,N+1): x[i]=mu(i)
D=N//4
ps=[None]*(D+1)
viol=[]
cost=0
def build():
    global viol,cost
    viol=[]; cost=0
    for d in range(1,D+1):
        L=N//d; arr=[0]*(L+1); s=0
        for k in range(1,L+1):
            s += x[k*d]; arr[k]=s
            if k>=4 and k%2==0 and abs(s)>3:
                viol.append((d,k)); cost += abs(s)-3
        ps[d]=arr
build()
print('init cost',cost,'viol',len(viol), flush=True)
# divisors for i up to D only where progression has >=4
Div=[[] for _ in range(N+1)]
for d in range(1,D+1):
    for j in range(d,N+1,d): Div[j].append(d)

def delta(i):
    dx=-2*x[i]; de=0
    for d in Div[i]:
        k0=i//d; arr=ps[d]; L=N//d
        t=k0 if k0%2==0 else k0+1
        if t<4: t=4
        for k in range(t,L+1,2):
            old=arr[k]; new=old+dx
            co=max(0,abs(old)-3); cn=max(0,abs(new)-3); de += cn-co
    return de

def apply(i):
    global cost
    dx=-2*x[i]; x[i] = -x[i]
    for d in Div[i]:
        k0=i//d; arr=ps[d]; L=N//d
        for k in range(k0,L+1): arr[k]+=dx
    # rebuild violations periodically exact

start=time.time(); best=cost; no=0
for it in range(200000):
    if cost==0: break
    if it%200==0:
        build()
        if cost<best: best=cost; print('it',it,'cost',cost,'viol',len(viol),'time',time.time()-start, flush=True)
    if not viol: break
    d,k=random.choice(viol)
    # sample vars in this bad prefix plus random
    besti=None; bestde=10**9
    for _ in range(40):
        if random.random()<0.8:
            idx=random.randint(1,k)*d
        else:
            idx=random.randint(1,N)
        de=delta(idx)
        if de<bestde: bestde=de; besti=idx
    if bestde<=0 or random.random()<math.exp(-bestde/max(0.1,5*(1-it/200000))):
        apply(besti); cost += bestde
print('final rebuild'); build(); print('final',cost,len(viol),'time',time.time()-start)
if cost==0:
    open('/workspace/edp_bits.txt','w').write(''.join('1' if x[i]>0 else '0' for i in range(1,N+1)))
