Sub topic 12
How many digits are used to write 1 to n
Assume you know place value, powers of 10, and basic arithmetic with ranges. This chapter counts the total number of written digits. It does not count how often one particular digit, such as 7, appears.
Count by place-value blocks
Numbers with the same number of digits form a block:
| Numbers | Count of numbers | Digits per number | Total digits |
|---|---|---|---|
| 1 to 9 | 9 | 1 | 9 |
| 10 to 99 | 90 | 2 | 180 |
| 100 to 999 | 900 | 3 | 2,700 |
The first one-digit block has 9 numbers. The two-digit block has \(99-10+1=90\) numbers. In general, the \(k\)-digit numbers run from \(10^{k-1}\) to \(10^k-1\), so there are
\[ 10^k-10^{k-1}=9\cdot10^{k-1} \]
such numbers. Each contributes \(k\) digits.
A general method
To count the digits used from 1 through \(n\):
- Count every complete block below the number of digits in \(n\).
- Count the final partial block.
- Add the results.
Suppose \(n=347\).
- Numbers from 1 to 9 use \(9\cdot1=9\) digits.
- Numbers from 10 to 99 use \(90\cdot2=180\) digits.
- Numbers from 100 to 347 contain \(347-100+1=248\) numbers. They use \(248\cdot3=744\) digits.
Therefore,
\[ 9+180+744=933. \]
The \(+1\) in \(347-100+1\) matters because both endpoints are included.
def digits_used(n):
if n <= 0:
return 0
total = 0
start = 1
width = 1
while start * 10 <= n:
count = 9 * start
total += count * width
start *= 10
width += 1
total += (n - start + 1) * width
return total
print(digits_used(99)) # 189
print(digits_used(347)) # 933The variable start stores the first number in the current block. For the last block, n - start + 1 gives the number of terms.
Counting a range
For a range from \(a\) to \(b\), subtract two prefix counts:
\[ \text{digits from }a\text{ to }b = F(b)-F(a-1), \]
where \(F(x)\) is the number of digits used from 1 through \(x\).
For example, the digits used from 25 to 120 are
\[ F(120)-F(24). \]
Here,
\[ F(120)=9+180+(120-100+1)\cdot3=252, \]
and
\[ F(24)=9+(24-10+1)\cdot2=39. \]
Thus the range uses \(252-39=213\) digits.
Quick checks
If \(n\) has \(d\) digits, the total should be roughly \(d n\), but it must be lower because many earlier numbers have fewer digits. Also check the boundary values:
- \(F(9)=9\)
- \(F(10)=11\)
- \(F(99)=189\)
- \(F(100)=192\)
At each power of 10, only one additional digit is added to the preceding total.
Exercise
How many digits are used to write all integers from 1 through 2,500?
Show answer
The complete blocks use 9 + 180 + 2,700 = 2,889 digits. The numbers 1,000 through 2,500 contain 1,501 four-digit numbers, using 6,004 digits. The total is 8,893 digits.