Lesson goal: Cryptarithmetic and digit divisibility

Previous: Principle of Inclusion-Exclusion | Home | Next: Digit sums and divisibility by 11

In the 1967 MAA High School Mathematics Contest (Problem #1), contestants solved this digit puzzle:

"The three-digit number $2a3$ is added to the number $326$ to give the three-digit number $5b9$. If $5b9$ is divisible by 9, then $a + b$ equals:"
(A) 2    (B) 4    (C) 6    (D) 7    (E) 9

In cryptarithmetic (or alphametics), letters stand for unknown decimal digits from $0$ through $9$.

Let's analyze the problem step-by-step:
  1. Place-value expansion: $$2a3 = 200 + 10a + 3 = 203 + 10a$$ $$5b9 = 500 + 10b + 9 = 509 + 10b$$
  2. Setting up the addition: $$(203 + 10a) + 326 = 509 + 10b$$ $$529 + 10a = 509 + 10b \implies 10b - 10a = 20 \implies b - a = 2 \implies b = a + 2$$ So digit $b$ is exactly 2 greater than digit $a$.
  3. The divisibility rule for 9: A number is divisible by 9 if and only if the sum of its digits is divisible by 9: $$\text{Digit sum of } 5b9 = 5 + b + 9 = 14 + b$$ Since $b$ is a single digit ($0 \le b \le 9$), $14 + b$ can only range from 14 to 23. The only multiple of 9 in this range is 18: $$14 + b = 18 \implies b = 4$$
  4. Finding $a$ and the final sum: $$a = b - 2 = 4 - 2 = 2$$ $$a + b = 2 + 4 = 6$$ The full equation is $223 + 326 = 549$, and $549 / 9 = 61$!
In this lesson, we write code to search through digit possibilities, test the constraints, and find the unique solution.
for a = 0, 9 do
  for b = 0, 9 do

    num1 = 200 + 10 * a + 3

    num2 = 500 + 10 * b + 9

    if num1 + 326 == num2 and num2 % 9 == 0 then

      print(a + b)
    end

  end
end
Move the mouse over a dotted box for more information.

  • Brute force search: There are only $10 \times 10 = 100$ possible pairs $(a, b)$. A computer tests all 100 in less than a microsecond!
  • Digit sum test: You can also verify divisibility by 9 directly from the digits: (5 + b + 9) % 9 == 0. This mathematical rule works because $10 \equiv 1 \pmod 9$, so $100d_2 + 10d_1 + d_0 \equiv d_2 + d_1 + d_0 \pmod 9$!

Now you try. Run the code to verify $a + b = 6$. Then try changing the second number to another value to see if a solution still exists!

Type your code here:


See your results here: