Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Digit DP

Counting the numbers up to N with a property, one digit at a time.

How many integers up to 101810^{18} have no two equal adjacent digits? Testing them one by one at a billion per second would take about thirty years. A digit DP answers in a millisecond, 168,856,464,709,124,010168{,}856{,}464{,}709{,}124{,}010, by building the numbers digit by digit and remembering only whether it is still glued to the bound, plus a little about the digits so far.

What you’ll learn

  • Count the integers in [0,N][0, N] with a digit property using the state (position, tight flag, extra state), and prove the count exact by splitting [0,N][0, N] at the first digit where xx differs from NN.
  • Handle leading zeros and two-sided ranges, and total quantities over all x≤Nx \le N with DPs that return (count, sum) pairs.
  • Count the numbers accepted by any finite automaton reading digits in O(bL∣Q∣)O(bL\abs{Q}) time, and combine properties with product automata.
  • Explain the limits of the method: non-regular properties such as primality, Cobham's theorem, and what is known about the digits of primes.

Building numbers under a bound

Let f(N)f(N) count the integers x∈[0,N]x \in [0, N] whose decimal digits have some property, for NN up to 101810^{18} or more. Write NN with LL digits N0N1⋯NL−1N_0 N_1 \cdots N_{L-1}, most significant first, and pad every x≤Nx \le N with leading zeros to LL digits.

Build xx from the left. While every digit so far equals NN's, the next digit can be at most NiN_i. As soon as one digit is smaller, x<Nx < N is settled and every later digit is free. One bit, the tight flag, records which case you are in; the rest of the state summarizes whatever the property needs to know about the digits placed so far.

python
from functools import cache

def count_digit_sum(N, k):                  # x in [0, N] whose digit sum is divisible by k
    d = list(map(int, str(N)))
    @cache
    def go(pos, rem, tight):                # rem = (digit sum so far) mod k
        if pos == len(d):
            return 1 if rem == 0 else 0
        limit = d[pos] if tight else 9
        return sum(go(pos + 1, (rem + c) % k, tight and c == limit)
                   for c in range(limit + 1))
    return go(0, 0, True)

At most 2Lk2Lk states, each trying at most 10 digits: O(10Lk)O(10Lk) time with L≈log⁡10NL \approx \log_{10} N. For N=2024N = 2024 and k=7k = 7 it returns 283, as a brute-force loop confirms. For N≤1018N \le 10^{18} and k=100k = 100 that is about 3,800 states and 38,000 steps.

Think first In count_digit_sum(N, k), how many different states with tight = True are ever visited? What does that say about which states are worth memoizing?

One per position: a tight state's prefix equals NN's prefix, so its remainder is determined. All the repetition happens in the free states. If the memo is indexed by the number of digits left instead of the position, the free table no longer depends on NN, and many queries with different bounds can share it.

Leading zeros, ranges and sums

Two-sided ranges. The count over [A,B][A, B] is f(B)−f(A−1)f(B) - f(A - 1), with f(−1)=0f(-1) = 0.

Leading zeros. Padding is harmless when the property ignores leading zeros, as digit sums and divisibility do. It is not harmless for "no two equal adjacent digits": 7 padded to 007 has two adjacent zeros. Add a flag started, false while only zeros have been placed: a zero placed before the number starts is not a digit of xx.

python
def count_no_equal_adjacent(N):             # x in [1, N] with no two equal adjacent digits
    d = list(map(int, str(N)))
    @cache
    def go(pos, last, tight, started):      # last digit placed, or -1 before x starts
        if pos == len(d):
            return 1 if started else 0      # x = 0 is not counted
        limit = d[pos] if tight else 9
        total = 0
        for c in range(limit + 1):
            if started and c == last:
                continue                    # two equal adjacent digits
            now = started or c != 0         # a leading zero does not start x
            total += go(pos + 1, c if now else -1, tight and c == limit, now)
        return total
    return go(0, -1, True, False)

About 44L44L states (11 values of last, two flags), 10 digits each. Up to 100 it counts 90 numbers, all but 11,22,…,9911, 22, \dots, 99 and 100100; up to 101810^{18} it counts the number in the hook.

Sums over the numbers. To total a quantity over all x≤Nx \le N, such as how many times the digit 1 is written in 0,1,…,N0, 1, \dots, N, let each state return a pair: how many completions it has, and the total of the quantity over them. A digit 1 placed at this position adds one to every one of the ww completions below it.

python
def count_ones(N):                          # how many digit 1s appear in 0, 1, ..., N
    d = list(map(int, str(N)))
    @cache
    def go(pos, tight):                     # (completions, total 1s written in them)
        if pos == len(d):
            return 1, 0
        limit = d[pos] if tight else 9
        ways = ones = 0
        for c in range(limit + 1):
            w, s = go(pos + 1, tight and c == limit)
            ways += w
            ones += s + (w if c == 1 else 0)   # this 1 is written in all w completions
        return ways, ones
    return go(0, True)[1]

O(10L)O(10L) time. It returns 6 for N=13N = 13 (the 1s of 1, 10, 11, 11, 12, 13) and 600,000 for N=999,999N = 999{,}999: each of the 6 positions shows a 1 in exactly a tenth of the 10610^6 numbers.

Predict before you look

How many times is the digit 1 written when you write out all the integers from 1 to 100?

Show the answer

21 ones

Units digits: 1, 11, 21, …, 91 give 10. Tens digits: 10 to 19 give 10 (11 is counted in both places, once for each 1). Hundreds digit: 100 gives 1. Total 10+10+1=2110 + 10 + 1 = 21, which is count_ones(100).

The automaton view

Every example so far is a finite automaton in disguise. A deterministic finite automaton (DFA) with states QQ, start state q0q_0, accepting states FF and transitions δ(q,c)\delta(q, c) reads the digits of xx from the left, and the property holds when it stops in FF. The extra DP state is the automaton's state:

PropertyAutomaton statesTransition on digit cc
digit sum divisible by kkZk\mathbb{Z}_k, the sum so far mod kkq↦(q+c) mod kq \mapsto (q + c) \bmod k
xx divisible by kkZk\mathbb{Z}_k, the prefix's value mod kkq↦(10q+c) mod kq \mapsto (10q + c) \bmod k
no substring "13"how much of "13" the last digits match: 0 or 1, plus a dead statethe string-matching automaton of the pattern
no two equal adjacent digitsthe last digit, or "not started"q↦cq \mapsto c, dead if c=qc = q
two properties at onceQ1×Q2Q_1 \times Q_2both transitions at once: the product automaton
Any finite pattern can be forbidden or required the same way, with the prefix-function automaton of the pattern; several patterns at once use the Aho–Corasick automaton.
DerivationProof: the decomposition, run through the automaton
  1. free[0][q]=[q∈F],free[m][q]=∑c=0b−1free[m−1][δ(q,c)]\text{free}[0][q] = [q \in F], \qquad \text{free}[m][q] = \sum_{c=0}^{b-1} \text{free}[m-1][\delta(q, c)]

    Let free[m][q]\text{free}[m][q] be the number of digit strings of length mm that drive the automaton from qq into FF:

  2. f(N)=[qL∈F]+∑i=0L−1 ∑c=0Ni−1free[L−i−1][δ(qi,c)]f(N) = [q_L \in F] + \sum_{i=0}^{L-1}\ \sum_{c=0}^{N_i - 1} \text{free}[L-i-1][\delta(q_i, c)]

    Let qiq_i be the state after reading N0⋯Ni−1N_0 \cdots N_{i-1}. The block of the decomposition with first difference at position ii and digit c<Nic < N_i continues from state δ(qi,c)\delta(q_i, c) with L−i−1L - i - 1 free digits, and NN itself is accepted iff qL∈Fq_L \in F:

  3. T(N)=O(bL∣Q∣)+O(bL)T(N) = O(bL\abs{Q}) + O(bL)

    The table has (L+1)∣Q∣(L+1)\abs{Q} entries of bb terms each, and the sum has at most bLbL terms:

python
def count_dfa(N, delta, start, accepting, Q):   # states 0..Q-1; delta(start, 0) == start
    d = list(map(int, str(N)))
    L = len(d)
    free = [[1 if q in accepting else 0 for q in range(Q)]]
    for m in range(1, L + 1):                   # free[m][q]: good suffixes of length m from q
        free.append([sum(free[m - 1][delta(q, c)] for c in range(10)) for q in range(Q)])
    total, q = 0, start
    for i, di in enumerate(d):          # x equals N before position i, then has c < d[i]
        for c in range(di):
            total += free[L - i - 1][delta(q, c)]
        q = delta(q, di)
    return total + (1 if q in accepting else 0)   # and x = N itself

The theorem as code, with no tight flag at all. With delta = lambda q, c: (10 * q + c) % 7, start 0, accepting {0} and 7 states, it counts the multiples of 7 in [0,1018][0, 10^{18}]: 142,857,142,857,142,858=⌊1018/7⌋+1142{,}857{,}142{,}857{,}142{,}858 = \lfloor 10^{18}/7 \rfloor + 1, counting 0.

Fix a parameter, then count. Some properties need a number the automaton cannot know in advance, such as "xx is divisible by its own digit sum". Loop over the digit sum s∈[1,9L]s \in [1, 9L], and for each ss count the xx whose digit sum is exactly ss and with x≡0(mods)x \equiv 0 \pmod s: an automaton with about s2s^2 states (the sum so far and the value mod ss). The total is ∑sO(10Ls2)=O(L4)\sum_s O(10Ls^2) = O(L^4) with a sizable constant, a few hundred million steps for NN near 101810^{18}. Up to 1000 there are 213 such numbers.

Check your understanding

Which of these properties of x≤1018x \le 10^{18} can not be counted by a digit DP with a small automaton?

  1. xx is divisible by 2024
  2. xx contains the digits 2024 consecutively
  3. the digits of xx never decrease from left to right
  4. xx is a prime number
Show the answer

D. xx is a prime number

The first three are recognized by automata with 2024 states (the value mod 2024), 5 states (how much of 2024 has been matched) and about 11 states (the last digit). The primes are not a regular language in any base, and counting them up to NN takes number theory: about N2/3N^{2/3} time with the Meissel–Lehmer method, N1/2+εN^{1/2 + \varepsilon} with analytic methods.

Limits and the research frontier

Digit DP counts exactly what finite automata see in the digits, and automata are tied to their base. "xx is a power of 2" is a three-state property in binary (a 1, then only 0s), yet no finite automaton recognizes it in decimal. The reason is a theorem.

A sequence computed by an automaton from the base-kk digits of nn is called kk-automatic (Allouche & Shallit, 2003); the Thue–Morse sequence, the parity of the number of 1-bits of nn, is the classic example. Digit DP computes prefix sums of any automatic sequence in O(log⁡N)O(\log N) time.

Primality is the famous count that digit DP cannot do. The Meissel–Lehmer method, as refined by Lagarias, Miller and Odlyzko (1985) and by Deléglise and Rivat (1996), computes the number of primes up to NN in about N2/3N^{2/3} time, and the analytic method of Lagarias and Odlyzko (1987) in N1/2+εN^{1/2 + \varepsilon}.

Key takeaways

  • A digit DP counts x≤Nx \le N with state (position, tight, extra): tight means the prefix still equals NN's, and once a smaller digit is placed the rest is free; this is the decomposition of [0,N][0, N] at the first differing digit.
  • Ranges are f(B)−f(A−1)f(B) - f(A - 1); a started flag keeps leading zeros from counting as digits; DPs that return (count, sum) pairs total quantities over all x≤Nx \le N.
  • Any property recognized by a DFA reading the digits is counted in O(bL∣Q∣)O(bL\abs{Q}) time: the extra DP state is the automaton's state, product automata combine properties, and parameters the automaton cannot know (such as a target digit sum) are fixed in an outer loop.
  • Digit DP stops at the regular languages: primality needs number theory, and by Cobham's theorem a set recognizable in two independent bases is ultimately periodic.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

f(N)f(N) counts the x∈[0,N]x \in [0, N] with a property. Which expression counts the x∈[A,B]x \in [A, B] with it, for 0≤A≤B0 \le A \le B?

  1. f(B)−f(A)f(B) - f(A)
  2. f(B)−f(A)+1f(B) - f(A) + 1
  3. f(B)−f(A−1)f(B) - f(A - 1), with f(−1)=0f(-1) = 0
  4. f(B−A)f(B - A)
Show the answer

C. f(B)−f(A−1)f(B) - f(A - 1), with f(−1)=0f(-1) = 0

f(B)f(B) counts [0,B][0, B] and f(A−1)f(A - 1) counts [0,A−1][0, A - 1]; the difference is exactly [A,B][A, B].

Question 2

For which property does padding xx with leading zeros change the count, unless the DP tracks whether the number has started?

  1. The digit sum of xx is divisible by 3
  2. xx is divisible by 7
  3. xx has no digit 5
  4. xx has no digit 0
Show the answer

D. xx has no digit 0

Padding inserts zeros: 7 becomes 007, which contains the digit 0 although 7 does not. The other properties are unchanged by leading zeros: they add nothing to a digit sum, nothing to a value, and no digit 5.

Question 3

In a digit DP for N=5,307N = 5{,}307, the digits 5, 2 have been placed. Which digits may come next?

  1. Only 0, since NN's next digit is 0
  2. Any digit 0–9: 52…<53…52\ldots < 53\ldots is already settled
  3. Digits 0–3
  4. None: 52 does not match NN's prefix
Show the answer

B. Any digit 0–9: 52…<53…52\ldots < 53\ldots is already settled

The second digit, 2, is below NN's 3, so x<Nx < N whatever follows: the tight flag is off and the remaining digits are free. The decomposition puts these numbers in the block "first difference at position 1 with digit 2".

Further reading

  • J.-P. Allouche & J. Shallit, Automatic Sequences: Theory, Applications, Generalizations (Cambridge University Press, 2003).
  • A. Cobham, "On the base-dependence of sets of numbers recognizable by finite automata," Mathematical Systems Theory 3 (1969).
  • M. Sipser, Introduction to the Theory of Computation, 3rd ed. (Cengage, 2012), chapter 1: finite automata and the product construction.
  • C. Mauduit & J. Rivat, "Sur un problème de Gelfond : la somme des chiffres des nombres premiers," Annals of Mathematics 171 (2010).
  • J. Maynard, "Primes with restricted digits," Inventiones Mathematicae 217 (2019).