Hyperbinary representations and their count
DefinitionCalkinWilf_hyperbinaryCountcombinatoricsnumber-theory
A hyperbinary representation of a nonnegative integer writes as a sum of powers of in which each power is used at most twice:
with only finitely many . For example, has two hyperbinary representations.
The function counts the hyperbinary representations of . Its values begin (OEIS A002487, shifted by one). Calkin and Wilf showed that the ratios list every positive rational exactly once.
Formalization Note A representation is a finitely supported multiplicity function c : ℕ →₀ ℕ with c i ≤ 2 and ∑ c i * 2^i = n, and hyperbinaryCount n is the Nat.card of the set of such c.
Definition code
import Mathlib
namespace CalkinWilf
/-- **Hyperbinary representation** (Calkin, Wilf, *Recounting the Rationals*, Amer. Math. Monthly
107 (2000), no. 4, p.361): a way "of writing the integer n as a sum of powers of 2, each power
being used at most twice". The finitely supported `c` gives the multiplicity `c i ∈ {0, 1, 2}` of
`2 ^ i`.
**Formalization Note** Representations are multiplicity functions `ℕ →₀ ℕ`, so two sums that
differ only in the order of their parts are the same representation. -/
def IsHyperbinaryRep (n : ℕ) (c : ℕ →₀ ℕ) : Prop :=
(∀ i, c i ≤ 2) ∧ (c.sum fun i k => k * 2 ^ i) = n
/-- **The hyperbinary counting function `b(n)`** (Calkin, Wilf, p.361): the number of hyperbinary
representations of `n`. Its values begin `1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, …` (OEIS A002487,
shifted by one).
**Formalization Note** `Nat.card` of the set of representations; the set is finite, since a
power `2 ^ i > n` cannot occur. -/
noncomputable def hyperbinaryCount (n : ℕ) : ℕ :=
Nat.card {c : ℕ →₀ ℕ // IsHyperbinaryRep n c}
end CalkinWilf
Source
Calkin–Wilf, Recounting the Rationals, Amer. Math. Monthly 107 (2000), no. 4, 360–363, https://www.jstor.org/stable/2589182, p. 361