We left off in part 2 with a program that could quickly compute
the total number of characters produced in any grammar. We will use
that program in this part to locate exactly where in the production
the nth letter is, in order to solve the following
slightly easier version of the puzzle:

If the integers from 1 to 999,999,999 are written as words in
order and concatenated, what is the 51 billionth letter?

(The alphabetical sorting was dropped.) This version has
appeared in some of ITA Software’s ads.

We solve this one by keeping track a binary tree corresponding
to the productions in the grammar, computing the total length of
each production and doing a search in this tree.

Note that the addition operation is not commutative. This is
impossible in a ring: in any ring the addition is necessarily
commutative. (Exercise!) But this does not hold in general for a
semiring (with no subtraction) or, more severely, for a semiring or
seminearring (which only has one of the two distributive laws).
This is fortunate for us, since we want to be sure to keep the
productions in order.

The multiplication operation is a little more subtle, since we
multiply two trees, either of which may branch. We use
left-to-right evaluation, taking by preference the branches of the
left tree.

Since in English the most significant digits are always on the
left, the resulting order of the leaves of the tree constructed for
ten9 will be the usual numerical order. If we were
working in a language where the least significant digits were
stated first, we would need right-to-left evaluation, or we could
go to a more general solution like the one we will later give for
alphabetical sorting.

We will use these trees to keep track of the count and volume of
the productions (as in part 2), as well as the list of strings (so
that we can see what letter we get).