# Compute Hofstadter G by shifting Fibonacci digits

Henry Shin · Refactor · Mathematical companion · November 27, 2026

Follow a nested lookup until Fibonacci numbers suggest how to write its input. A carry proves the digit rule, and the smallest occupied place controls the error of a linear estimate.

To compute the eleventh term of Hofstadter’s G sequence, the tenth term tells us where to look. It is 6, so we open the sixth entry, find 4, and subtract it from 11. Can we get the same 7 by working on the digits of 11 itself?

## Follow the nested lookup

Douglas Hofstadter starts with G(0) = 0 and gives the next value by

G(n + 1) = n + 1 − G(G(n)).

The inner call supplies an address. The outer call reads the value stored there. These addresses are always legal. Suppose 0 ≤ G(j) ≤ j for all j up to n. Then G(n) is an address between 0 and n, and the value found there lies between 0 and G(n). The subtraction gives 1 ≤ G(n + 1) ≤ n + 1. Starting at zero, this proves that the rule determines every entry uniquely.

Computing from index 0 through index 13 gives

0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8.

Which indices are worth trying next? Imagine G(n) grows roughly like αn. The nested call would then grow like α²n, so the rough slopes would obey α + α² = 1, or α = 1/(1 + α). Applying the right side to a fraction p/q sends it to q/(p + q). Starting at 1/2 gives 2/3, 3/5, 5/8, 8/13. Now look at those denominators in the computed row. G sends 2, 3, 5, 8, 13 to 1, 2, 3, 5, 8. The predicted numerators are exact at every one of these indices.

## Try the rule between Fibonacci indices

Write F₀ = 0, F₁ = F₂ = 1, and F_{j+2} = F_{j+1} + F_{j}. For j ≥ 2, the row suggests G(F_{j}) = F_{j−1}. Try decomposing a new index into Fibonacci terms and moving each term back one place. For 7 = 5 + 2 this gives 3 + 1 = 4. For 11 = 8 + 3 it gives 5 + 2 = 7. Both agree with the nested lookups. Arbitrary sums need care. Writing 2 as 1 + 1 would return 1 + 1, while treating 2 as F₃ returns the correct 1.

Use the Zeckendorf expansion of n. Choose terms from F₂, F₃, F₄, …, using each position at most once and leaving at least one empty position between chosen terms. Zero uses the empty sum. These rules give every integer a unique spelling. In fact the digits through F_{j} spell exactly the integers from 0 through F_{j+1} − 1, once each. This holds with no digits, and with just F₂. Inductively, omitting F_{j} gives the integers below F_{j}. Using it forces us to omit F_{j−1}, so the smaller digits add any integer from 0 through F_{j−1} − 1. The two intervals meet end to end because F_{j} + F_{j−1} = F_{j+1}.

Call the proposed operation D. Given the expansion of n, replace each F_{j} by F_{j−1} and add. At the bottom, F₂ becomes F₁, whose value is still 1. Thus D(12) shifts 8 + 3 + 1 to 5 + 2 + 1, giving 8. Before shifting a second time, we spell 8 in its canonical form, a single Fibonacci term. This gives D(D(12)) = 5. Since D(13) = 8, the required sum D(13) + D(D(12)) is indeed 8 + 5 = 13.

[Try the Fibonacci digit shift in the web edition](https://refactor.press/refactors/hofstadter-g#shift-the-digits).

## Prove the digit shift by following one carry

To verify the nested recurrence we need D(n + 1) and D(D(n)). In both calculations the lowest digit can force a carry. What can rewriting a sum do to its shifted value? Two neighboring terms F_{j} and F_{j+1} combine into F_{j+2}. Shifting before the combination gives the same answer as shifting afterward, since F_{j−1} + F_{j} = F_{j+1}. This equality holds even for j = 2.

Let e be 1 if n uses the lowest digit F₂, and 0 otherwise. Adding a unit to n means inserting an F₂. When e = 0, the inserted term contributes 1 to the shifted value. When e = 1, first replace F₂ + F₂ by F₃. The two copies would shift to 1 + 1, while F₃ shifts to 1, costing exactly one unit. Any remaining carry joins adjacent terms and preserves the shifted value. Only the moving term can meet a neighbor, and the position above that neighbor was empty. Each merge removes a term, so the carries end in canonical digits. We have obtained

D(n + 1) = D(n) + 1 − e.

Now shift n twice. Away from the bottom, each original F_{j} contributes F_{j−2} = F_{j} − F_{j−1}. These differences would sum to n − D(n). The exception is an original F₂. On the first shift it becomes F₁ = 1. To write the result in canonical digits we label this unit F₂ again. It now contributes 1 on the second shift, one more than F₂ − F₁ = 0. The original F₂ excluded F₃, so there is no other copy of F₂ after the first shift. Relabeling the unit can bring it next to F₃, but each adjacent carry preserves the value of the next shift, by the same identity above. Hence

D(D(n)) = n − D(n) + e.

Add the two equations. The contribution of the lowest digit cancels, leaving D(n + 1) + D(D(n)) = n + 1. The empty sum gives D(0) = 0. We have constructed a function with Hofstadter’s initial value and recurrence, which determine a unique function. Thus G(n) is the sum obtained by shifting the Fibonacci terms of n back one position.

Pierre Letouzey proves this shift rule for a wider class of Fibonacci expansions in [Hofstadter’s problem for curious readers, Theorem 14](https://arxiv.org/html/1509.02479#Thmtheorem14).

## How close is the shift to a straight line?

Moving a digit from F_{i} to F_{i−1} almost multiplies its value by α = (√5 − 1)/2 = 1/φ. The error in that approximation is a quantity we already know. In the [Fibonacci recurrence](https://refactor.press/refactors/recurrence#two-independent-motions), the weighted difference u_{i} = F_{i} − φF_{i−1} changes sign and shrinks by a factor of α at every step. Multiply it by −α and use αφ = 1. This gives the exact error from shifting one digit.

e_{i} = F_{i−1} − αF_{i} = −αu_{i} = (−α)^{i}.

You can check the normalization at the lowest place. Shifting F₂ gives 1, so e₂ = 1 − α = α². Every following place multiplies that error by −α. What happens to a whole number? Its occupied digits each contribute one copy of the decaying Fibonacci mode. If I is the set of their indices, adding these contributions gives

G(n) − αn = ∑_{i ∈ I} (−α)^{i}.

The even indices contribute less than the full sum α² + α⁴ + ⋯ = α. The odd indices subtract less than α³ + α⁵ + ⋯ = α². Both inequalities are strict because the digit string is finite. Thus −α² < G(n) − αn < α. Since α + α² = 1, adding α to αn puts the result in the open unit interval above G(n).

G(n) < α(n + 1) < G(n) + 1,   hence   G(n) = ⌊α(n + 1)⌋.

### The smallest occupied index decides the sign

For n > 0, let j be the smallest index in I. The jth digit contributes (−α)^{j}. The next digit of the opposite sign can only occur at j + 3 or later, because j + 1 is forbidden. Even if we took every possible opposite-sign term, their magnitudes would sum to α^{j+3}/(1 − α²) = α^{j+2}. Taking every term of the original sign, starting at j, would sum to α^{j}/(1 − α²) = α^{j−1}. Subtracting the first bound from the leading digit gives

α^{j+1} < (−1)^{j}(G(n) − αn) < α^{j−1}.

Both endpoints are sharp. Keeping the indices j, j + 2, j + 4, … and extending the finite list approaches the upper endpoint. Keeping j, j + 3, j + 5, … approaches the lower one. An even j puts G(n) above αn, and an odd j puts it below. When j ≥ 3 the error is smaller than α² < ½, so ordinary rounding of the exact real number αn recovers G(n). At n = 4 = F₄ + F₂, rounding 4α ≈ 2.472 gives 2 while the digit shift gives F₃ + F₁ = 3.

## Get one value using integer arithmetic

How accurate must a real-valued calculation be before we take its floor? At n = F_{2k} − 1, the number inside the floor is F_{2k−1} − α^{2k}. For k ≥ 1 its nearest integer boundary is the one above it. An absolute error smaller than α^{2k} guarantees the correct floor. An upward error of exactly that size changes the answer. The gap shrinks at every even Fibonacci index.

At n = 102,334,154, the extra one inside the floor gives n + 1 = F₄₀. The single-digit error identity gives αF₄₀ = F₃₉ − α⁴⁰, just below 63,245,986. The exact answer is 63,245,985. Evaluated in Node.js using binary64 arithmetic, Math.floor((n + 1) * ((Math.sqrt(5) - 1) / 2)) gives 63,245,986. The input integer fits exactly. Rounding the real-valued calculation has erased which side of the integer the product lies on.

For a nonnegative integer supplied in binary, we can evaluate the same floor with an integer square root. Write t = n + 1 and choose the integer r satisfying r² ≤ 5t² < (r + 1)². Then αt lies in [(r − t)/2, (r − t + 1)/2). Whether r − t is even or odd, every number in this half-open interval has the same floor.

```text
from math import isqrt

def hofstadter_g(n):
    """Return G(n) for a nonnegative integer n."""
    t = n + 1
    return (isqrt(5 * t * t) - t) // 2
```

If t has b bits, the square-root input has at most 2b + 3 bits. The arithmetic cost depends on how those integers are multiplied and square-rooted. With Fibonacci digits already in hand, summing their shifted weights answers the same query using additions. To obtain the digits from an ordinary integer, grow consecutive Fibonacci numbers past n, then walk the pair backward by subtraction. Whenever a weight fits in the remainder, subtract it and add its predecessor to the answer. This takes O(b) additions, subtractions, and comparisons on O(b)-bit integers, hence O(b²) elementary bit operations with ordinary addition. Either procedure can answer a single query without building the preceding sequence.

## Sources and related reading

Douglas Hofstadter introduced G in Gödel, Escher, Bach. D. S. Meek and G. H. J. van Rees treat a family with more nested calls by translating the origin and truncating a generalized Fibonacci expansion. Pierre Letouzey gives a direct shift theorem for the untranslated family and studies how its discrepancy from linear growth changes with nesting depth. See [The Solution of an Iterated Recurrence (1984)](https://www.fq.math.ca/Scanned/22-2/meek.pdf) and [Generalized Hofstadter functions G, H and beyond, §§4 and 8](https://arxiv.org/html/2502.12615v5).

In [the Fibonacci pair test](https://refactor.press/refactors/recurrence.html#recognize-a-fibonacci-pair), two weighted differences recognize a pair of consecutive terms. Here the Fibonacci numbers themselves supply the place values for the address of a nested call. In [the merging-modes companion](https://refactor.press/refactors/when-two-modes-merge.html#two-or-zero), rounding erases the gap between two roots. For G, rounding can move the value across the integer boundary that determines its floor.

What if a small error can enter at every place and every step? In [Which grid errors reach the thermometer?](https://refactor.press/refactors/heat-grid), three weights track what each cell contributes to a final temperature reading. Their signs give the largest error the reading can have.
