Digit DP
Counting the numbers up to N with a property, one digit at a time.
How many integers up to 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, , 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 with a digit property using the state (position, tight flag, extra state), and prove the count exact by splitting at the first digit where differs from .
- Handle leading zeros and two-sided ranges, and total quantities over all with DPs that return (count, sum) pairs.
- Count the numbers accepted by any finite automaton reading digits in 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 count the integers whose decimal digits have some property, for up to or more. Write with digits , most significant first, and pad every with leading zeros to digits.
Build from the left. While every digit so far equals 's, the next digit can be at most . As soon as one digit is smaller, 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.
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 states, each trying at most 10 digits: time with . For and it returns 283, as a brute-force loop confirms. For and 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 '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 , and many queries with different bounds can share it.
Leading zeros, ranges and sums
Two-sided ranges. The count over is , with .
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 .
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 states (11 values of last, two flags), 10 digits each. Up to 100 it counts 90 numbers, all but and ; up to it counts the number in the hook.
Sums over the numbers. To total a quantity over all , such as how many times the digit 1 is written in , 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 completions below it.
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]time. It returns 6 for (the 1s of 1, 10, 11, 11, 12, 13) and 600,000 for : each of the 6 positions shows a 1 in exactly a tenth of the numbers.
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 , 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 , start state , accepting states and transitions reads the digits of from the left, and the property holds when it stops in . The extra DP state is the automaton's state:
| Property | Automaton states | Transition on digit |
|---|---|---|
| digit sum divisible by | , the sum so far mod | |
| divisible by | , the prefix's value mod | |
| no substring "13" | how much of "13" the last digits match: 0 or 1, plus a dead state | the string-matching automaton of the pattern |
| no two equal adjacent digits | the last digit, or "not started" | , dead if |
| two properties at once | both transitions at once: the product automaton |
Let be the number of digit strings of length that drive the automaton from into :
Let be the state after reading . The block of the decomposition with first difference at position and digit continues from state with free digits, and itself is accepted iff :
The table has entries of terms each, and the sum has at most terms:
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 itselfThe 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 : , counting 0.
Fix a parameter, then count. Some properties need a number the automaton cannot know in advance, such as " is divisible by its own digit sum". Loop over the digit sum , and for each count the whose digit sum is exactly and with : an automaton with about states (the sum so far and the value mod ). The total is with a sizable constant, a few hundred million steps for near . Up to 1000 there are 213 such numbers.
Which of these properties of can not be counted by a digit DP with a small automaton?
- is divisible by 2024
- contains the digits 2024 consecutively
- the digits of never decrease from left to right
- is a prime number
Show the answer
D. 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 takes number theory: about time with the Meissel–Lehmer method, 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. " 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- digits of is called -automatic (Allouche & Shallit, 2003); the Thue–Morse sequence, the parity of the number of 1-bits of , is the classic example. Digit DP computes prefix sums of any automatic sequence in 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 in about time, and the analytic method of Lagarias and Odlyzko (1987) in .
Key takeaways
- A digit DP counts with state (position, tight, extra): tight means the prefix still equals 's, and once a smaller digit is placed the rest is free; this is the decomposition of at the first differing digit.
- Ranges are ; a started flag keeps leading zeros from counting as digits; DPs that return (count, sum) pairs total quantities over all .
- Any property recognized by a DFA reading the digits is counted in 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.
counts the with a property. Which expression counts the with it, for ?
- , with
Show the answer
C. , with
counts and counts ; the difference is exactly .
For which property does padding with leading zeros change the count, unless the DP tracks whether the number has started?
- The digit sum of is divisible by 3
- is divisible by 7
- has no digit 5
- has no digit 0
Show the answer
D. 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.
In a digit DP for , the digits 5, 2 have been placed. Which digits may come next?
- Only 0, since 's next digit is 0
- Any digit 0–9: is already settled
- Digits 0–3
- None: 52 does not match 's prefix
Show the answer
B. Any digit 0–9: is already settled
The second digit, 2, is below 's 3, so 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).