import math,sys
LIM=int(sys.argv[1])
sieve=bytearray([1])*(LIM+1); sieve[0]=sieve[1]=0
for i in range(2,math.isqrt(LIM)+1):
    if sieve[i]: sieve[i*i::i]=bytearray(len(sieve[i*i::i]))
def theta(c):  # counts of c*x^2 = n
    t=[0]*(LIM+1); x=0
    while c*x*x<=LIM: t[c*x*x]+= 1 if x==0 else 2; x+=1
    return t
def conv(A,B):
    C=[0]*(LIM+1); nzB=[(j,b) for j,b in enumerate(B) if b]
    for i,a in enumerate(A):
        if a:
            for j,b in nzB:
                if i+j>LIM: break
                C[i+j]+=a*b
    return C
def form(cs):
    T=theta(cs[0])
    for c in cs[1:]: T=conv(T,theta(c))
    return T
G1=form([1,2,2,16]);G2=form([1,2,2,64]);H2=form([1,1,1,64])
bad=n5=n3=0
for p in range(3,LIM+1):
    if not sieve[p]: continue
    if p%8==5:
        b=next(b for b in range(1,LIM) if math.isqrt(p-4*b*b)**2==p-4*b*b); a=math.isqrt(p-4*b*b)
        a=a if a%4==1 else -a; b=b if b%4==1 else -b; n5+=1
        if G1[p]!=p+1+2*a or 2*G2[p]!=p+1+2*a+8*b: bad+=1; print("fail5",p,a,b,G1[p],G2[p])
    elif p%8==3:
        b=next(b for b in range(1,LIM) if math.isqrt(p-2*b*b)**2==p-2*b*b); a=math.isqrt(p-2*b*b)
        a=a if a%8 in (1,3) else -a; n3+=1
        if H2[p]!=p+1+4*a: bad+=1; print("fail3",p,a,b,H2[p])
print("LIM",LIM,"primes 5 mod 8:",n5,"primes 3 mod 8:",n3,"failures:",bad)
