#!/usr/bin/env python3
"""OEIS A349787 (Zhi-Wei Sun, 2021).

Conjecture 1: every n >= 2 is x^2 + y^k + 2^a + 2^b with x >= y >= 0, a >= b >= 0, k in {2, 3}.
Conjecture 2: every n >= 2 is a sum of two perfect powers (0 and 1 allowed) and two powers of 2.

This script shows, with plain integer arithmetic, that n = 60104967 has no representation of
either kind, and (with --least) that it is the smallest n >= 2 failing Conjecture 1, hence also
the smallest failing Conjecture 2, since a failure of Conjecture 2 is a failure of Conjecture 1.
"""
import math, sys

N = 60104967

def conj1(n):
    for a in range(n.bit_length() + 1):
        for b in range(a + 1):
            m = n - (1 << a) - (1 << b)
            if m < 0: continue
            y = 0
            while y * y <= m:
                for k in (2, 3):
                    r = m - y ** k
                    if r >= 0 and math.isqrt(r) ** 2 == r and math.isqrt(r) >= y:
                        return (math.isqrt(r), y, k, a, b)
                y += 1
    return None

def conj2(n):
    powers = {0, 1}
    for e in range(2, n.bit_length() + 1):
        base = 2
        while base ** e <= n: powers.add(base ** e); base += 1
    for a in range(n.bit_length() + 1):
        for b in range(a + 1):
            m = n - (1 << a) - (1 << b)
            if m < 0: continue
            for p in powers:
                if p <= m and (m - p) in powers: return (p, m - p, a, b)
    return None

def least():
    import numpy as np
    S = np.zeros(N + 1, dtype=bool)                 # x^2 + y^2 or x^2 + y^3, x >= y >= 0
    for x in range(math.isqrt(N) + 1):
        y = np.arange(0, x + 1, dtype=np.int64)
        v = x * x + y * y; S[v[v <= N]] = True
        y3 = y[y <= 392]; v = x * x + y3 ** 3; S[v[v <= N]] = True
    ok = np.zeros(N + 1, dtype=bool)
    for a in range(27):
        for b in range(a + 1):
            s = (1 << a) + (1 << b)
            if s <= N: ok[s:] |= S[:N + 1 - s]
    return [int(n) for n in np.nonzero(~ok[2:])[0] + 2]

if __name__ == "__main__":
    print("535903 (the example in the entry):", conj1(535903))
    print(N - 1, "->", conj1(N - 1), "|", conj2(N - 1))
    print(N, "-> Conjecture 1:", conj1(N), "| Conjecture 2:", conj2(N))
    if "--least" in sys.argv:
        print("all n in [2, %d] with no Conjecture 1 representation:" % N, least())
