# Even numbers that are unitary Zumkeller but not unitary half-Zumkeller.
#
#   julia -t auto search.jl                  all even n <= 492011520 (about 1 GB of memory)
#   LIMIT=4000000000 julia -t auto search.jl a larger range (8 GB of memory, slower)
#   VERIFY=1 julia -t auto search.jl         also confirm every answer "not unitary Zumkeller"
#                                            by the second method
#
# Julia 1.9 or later, no packages.
#
# Write n = 2^k m with m odd and let U(m) be the set of the unitary divisors of m, with sum S.
# The unitary divisors of n are the elements of U(m) and their multiples by 2^k.
#
#   n is unitary Zumkeller       iff  some proper unitary divisors of n sum to sigma*(n)/2 - n,
#   n is unitary half-Zumkeller  iff  some proper unitary divisors of n sum to (sigma*(n) - n)/2,
#
# where sigma*(n) = (2^k + 1) S. Only n with sigma*(n) >= 2n can be unitary Zumkeller.
#
# Two methods decide these subset sum problems.
#
#   1. A depth first search over the proper unitary divisors in decreasing order. It answers
#      "yes" with a subset, "no" after an exhaustive search, or gives up after BUDGET nodes.
#   2. An exact method for the cases in which the search gives up: a sum of unitary divisors
#      of n is x + 2^k y with x and y sums of elements of U(m), and the set of all sums of
#      elements of U(m) is computed, as a sorted list or as a bit set.

using Base.Threads

const LIMIT = parse(Int, get(ENV, "LIMIT", "492011520"))
const BUDGET = parse(Int, get(ENV, "BUDGET", "200000"))
const VERIFY = get(ENV, "VERIFY", "0") == "1"

# smallest prime factor of every number up to M
function sieve(M::Int)
    spf = zeros(UInt32, M)
    @inbounds for i in 2:isqrt(M)
        if spf[i] == 0
            for j in i*i:i:M
                if spf[j] == 0
                    spf[j] = i
                end
            end
        end
    end
    @inbounds for i in 2:M
        if spf[i] == 0
            spf[i] = i
        end
    end
    return spf
end

# the prime powers that exactly divide m
function components!(comps::Vector{Int}, spf::Vector{UInt32}, m::Int)
    empty!(comps)
    @inbounds while m > 1
        p = Int(spf[m]); q = 1
        while m % p == 0
            m ÷= p; q *= p
        end
        push!(comps, q)
    end
    return comps
end

# the unitary divisors: all products of the components
function udivs!(ds::Vector{Int}, comps::Vector{Int})
    empty!(ds); push!(ds, 1)
    for q in comps
        len = length(ds)
        @inbounds for i in 1:len
            push!(ds, ds[i] * q)
        end
    end
    return ds
end

# ---------- method 1: depth first search ----------
# D is decreasing, suf[i] = D[i] + ... + D[end].  1 = found, 0 = no solution, -1 = gave up
function dfs(D::Vector{Int}, suf::Vector{Int}, nd::Int, i::Int, r::Int, cnt::Base.RefValue{Int})
    r == 0 && return 1
    i > nd && return 0
    @inbounds s = suf[i]
    r > s && return 0
    r == s && return 1
    cnt[] += 1
    cnt[] > BUDGET && return -1
    @inbounds d = D[i]
    if d <= r
        res = dfs(D, suf, nd, i + 1, r - d, cnt)
        res != 0 && return res
    end
    return dfs(D, suf, nd, i + 1, r, cnt)
end

function try_dfs(D::Vector{Int}, suf::Vector{Int}, target::Int)
    target < 0 && return 0
    nd = length(D)
    resize!(suf, nd + 1)
    suf[nd + 1] = 0
    @inbounds for i in nd:-1:1
        suf[i] = suf[i + 1] + D[i]
    end
    return dfs(D, suf, nd, 1, target, Ref(0))
end

# ---------- method 2: all sums of unitary divisors of the odd part ----------
function all_sums(vals::Vector{Int})
    sums = Int[0]
    for v in vals
        len = length(sums)
        @inbounds for i in 1:len
            push!(sums, sums[i] + v)
        end
    end
    sort!(sums); unique!(sums)
    return sums
end
in_sorted(v::Int, a::Vector{Int}) = (i = searchsortedfirst(a, v); i <= length(a) && @inbounds(a[i]) == v)

# bit set of the subset sums of vals; tot is the sum of vals
function bitset_sums(vals::Vector{Int}, tot::Int)
    nw = (tot >> 6) + 1
    w = zeros(UInt64, nw)
    w[1] = 1
    cur = 0
    for v in sort(vals)
        ws = v >> 6; bs = v & 63
        hi = min(nw, ((cur + v) >> 6) + 1)
        @inbounds for i in hi:-1:(ws + 1)          # w |= w << v
            x = w[i - ws] << bs
            if bs != 0 && i - ws - 1 >= 1
                x |= w[i - ws - 1] >> (64 - bs)
            end
            w[i] |= x
        end
        cur += v
    end
    return w
end
getbit(w::Vector{UInt64}, v::Int) = v >= 0 && (v >> 6) < length(w) && ((@inbounds w[(v >> 6) + 1]) >> (v & 63)) & 1 == 1

# (unitary Zumkeller, unitary half-Zumkeller) for n = 2^k m, where um = U(m)
function exact(um::Vector{Int}, m::Int, k::Int)
    S = sum(um)
    T = ((1 << k) + 1) * S ÷ 2            # sigma*(n)/2
    Th = T - (1 << (k - 1)) * m           # (sigma*(n) - n)/2
    um0 = filter(!=(m), um)               # x ranges over sums of U(m), y over sums of U(m) \ {m}
    if length(um0) <= 15
        A0 = all_sums(um0)
        inA0 = v -> in_sorted(v, A0)
        inA = v -> in_sorted(v, A0) || in_sorted(v - m, A0)
        uz = false; uhz = false
        for base in (0, m), a in A0
            x = a + base
            r = T - x
            if !uz && r >= 0 && (r & ((1 << k) - 1)) == 0 && inA(r >> k)
                uz = true
            end
            r = Th - x
            if !uhz && r >= 0 && (r & ((1 << k) - 1)) == 0 && inA0(r >> k)
                uhz = true
            end
        end
        return uz, uhz
    else
        w = bitset_sums(um0, S - m)
        inA0 = v -> (v <= S - m) && getbit(w, v)
        inA = v -> inA0(v) || (v >= m && inA0(v - m))
        uz = false; uhz = false
        for y in 0:S
            if inA(y)
                x = T - (y << k)
                x < 0 && break
                if x <= S && inA(x)
                    uz = true; break
                end
            end
        end
        for y in 0:(S - m)
            if inA0(y)
                x = Th - (y << k)
                x < 0 && break
                if x <= S && inA(x)
                    uhz = true; break
                end
            end
        end
        return uz, uhz
    end
end

# all n = 2^k m <= LIMIT with m odd, mlo <= m <= mhi
function process_range(spf::Vector{UInt32}, mlo::Int, mhi::Int)
    comps = Int[]; um = Int[]; D = Int[]; suf = Int[]
    nuz = 0; nexact = 0; nnot = 0; nmis = 0
    bad = Tuple{Int,Int,Int}[]            # (n, m, k)
    m = isodd(mlo) ? mlo : mlo + 1
    while m <= mhi
        components!(comps, spf, m)
        udivs!(um, comps)
        S = sum(um)
        k = 1
        while (m << k) <= LIMIT
            p2 = 1 << k
            # sigma*(n) >= 2n is necessary; sigma*(n)/n decreases in k
            if (p2 + 1) * S < 2 * p2 * m
                break
            end
            n = m << k
            empty!(D)                     # the proper unitary divisors of n
            for d in um
                push!(D, d)
                d != m && push!(D, d << k)
            end
            sort!(D, rev = true)
            T = (p2 + 1) * S ÷ 2
            r1 = try_dfs(D, suf, T - n)
            uz = r1 == 1; uhz = false; decided = r1 >= 0
            if decided && uz
                r2 = try_dfs(D, suf, T - (n >> 1))
                if r2 >= 0
                    uhz = r2 == 1
                else
                    decided = false
                end
            end
            if !decided
                uz, uhz = exact(um, m, k)
                nexact += 1
            elseif !uz
                nnot += 1
                if VERIFY && exact(um, m, k)[1]
                    nmis += 1
                    println("the two methods disagree at n = $n")
                end
            end
            if uz
                nuz += 1
                uhz || push!(bad, (n, m, k))
            end
            k += 1
        end
        m += 2
    end
    return nuz, nexact, nnot, nmis, bad
end

function main()
    M = LIMIT ÷ 2
    t0 = time()
    spf = sieve(M)
    chunk = 200_000
    starts = collect(3:chunk:M)
    results = Vector{Any}(undef, length(starts))
    @threads :dynamic for i in eachindex(starts)
        lo = starts[i]
        results[i] = process_range(spf, lo, min(M, lo + chunk - 1))
    end
    nuz = sum(r[1] for r in results); nexact = sum(r[2] for r in results)
    nnot = sum(r[3] for r in results); nmis = sum(r[4] for r in results)
    bad = sort(vcat([r[5] for r in results]...))
    println("even n <= $LIMIT with sigma*(n) >= 2n: $(nuz + nnot)")
    println("  not unitary Zumkeller: $nnot", VERIFY ? " (contradicted by the second method: $nmis)" : "")
    println("  unitary Zumkeller: $nuz (decided by the second method: $nexact)")
    println("  unitary Zumkeller and not unitary half-Zumkeller: $(length(bad))")
    for (n, m, k) in bad
        println("    $n = 2^$k * $m")
    end
    println("time: $(round(time() - t0, digits = 1)) s")
end

main()
