Lesson goal: Four-digit numbers with end difference of 2

Previous: Minimum digit quotient | Home | Next: The Goldbach partition gap on 126

In the 1982 MAA Annual High School Mathematics Examination (Problem #11), contestants solved this counting challenge:

"How many integers with four different digits are there between 1,000 and 9,999 such that the absolute value of the difference between the first digit and the last digit is 2? (A) 672 (B) 784 (C) 840 (D) 896 (E) 1,008."

Let the four-digit integer be written as $d_1 d_2 d_3 d_4$, where each $d_i \in \{0, 1, \dots, 9\}$. Because the number is between 1,000 and 9,999:
  • The thousands digit $d_1$ cannot be zero ($1 \le d_1 \le 9$).
  • All four digits must be distinct: $d_1, d_2, d_3, d_4$ are all different.
  • The first and last digits must satisfy $|d_1 - d_4| = 2$.
Let's analyze the possible pairs $(d_1, d_4)$:
  1. If $d_1 = 1$: $d_4$ can only be $3$ ($1$ pair).
  2. If $d_1 = 2$: $d_4$ can be $0$ or $4$ ($2$ pairs).
  3. If $d_1 \in \{3, 4, 5, 6, 7\}$: $d_4 = d_1 - 2$ or $d_4 = d_1 + 2$ ($5 \times 2 = 10$ pairs).
  4. If $d_1 = 8$: $d_4$ can only be $6$ because $8 + 2 = 10$ is not a single digit ($1$ pair).
  5. If $d_1 = 9$: $d_4$ can only be $7$ ($1$ pair).
Adding these up gives $1 + 2 + 10 + 1 + 1 = 15$ possible pairs for $(d_1, d_4)$.

Now, for each of these 15 pairs:
  • $d_2$ can be any of the remaining $10 - 2 = 8$ digits.
  • $d_3$ can be any of the remaining $10 - 3 = 7$ digits.
By the fundamental counting principle, the total number of such integers is: $$\text{Total} = 15 \times 8 \times 7 = 15 \times 56 = \mathbf{840}$$

In this lesson, we write a program to extract individual digits using integer division and modulo arithmetic, filter out duplicates, and verify the counting formula!

Now you try. Replace ???? with 2 and run the code to verify that exactly 840 numbers match.

Type your code here:


See your results here: