"""Stanley's question (MO 431075): G = 1,1,2,3,4,9,8,27,...  (G_{2i+1} = 2^i, G_{2i+2} = 3^i).
P_n(x) = prod_{i<=n} (1 + x^{G_i}).  nu_1(n) = number of coefficients of P_n equal to 1.
Claim: nu_1(2I) = 2^(I - j0 + 1) with j0 = least j with 3^j >= 2^(I+1) - 1,  for I >= 1."""
import sys
from collections import Counter

def G(n):                      # 1-indexed
    i = (n - 1) // 2
    return 2 ** i if n % 2 == 1 else 3 ** i

def nu(n, k=1):
    coeffs = Counter({0: 1})
    for i in range(1, n + 1):
        g = G(i); new = Counter(coeffs)
        for e, c in coeffs.items(): new[e + g] += c
        coeffs = new
    return sum(1 for c in coeffs.values() if c == k)

def formula(I):
    j = 0
    while 3 ** j < 2 ** (I + 1) - 1: j += 1
    return 2 ** (I - j + 1)

N = int(sys.argv[1]) if len(sys.argv) > 1 else 12
print('G =', [G(n) for n in range(1, 13)])
vals = []
for I in range(1, N + 1):
    v = nu(2 * I); vals.append(v)
    print(f'I={I:2d}  nu_1(2I) = {v:6d}   formula = {formula(I):6d}   {"ok" if v == formula(I) else "MISMATCH"}')
print('ratios nu_1(2I+2)/nu_1(2I):', [vals[i + 1] // vals[i] for i in range(len(vals) - 1)])
print('all nu_1(n), n = 1..', 2 * min(N, 9), ':', [nu(n) for n in range(1, 2 * min(N, 9) + 1)])
