Lesson goal: Cryptarithmetic Puzzles & Constraints

Previous: Making coin change and backtracking | Home | Next: Propositional logic and truth tables

A cryptarithmetic puzzle (also known as an alphametic) is a mathematical brainteaser where digits are replaced with letters:
$$\begin{array}{r@{\quad}c@{\quad}c@{\quad}c} & \text{T} & \text{W} & \text{O} \\ + & \text{T} & \text{W} & \text{O} \\ \hline \text{F} & \text{O} & \text{U} & \text{R} \end{array}$$

The Rules:

  1. Each distinct letter represents a unique decimal digit from $0$ to $9$.
  2. Leading digits cannot be zero ($\text{T} \neq 0$ and $\text{F} \neq 0$).
  3. The addition must be mathematically correct!

Mathematical Deductions:

  • The Thousands Carry: Adding two 3-digit numbers can produce at most $999 + 999 = 1998$. Therefore, the carry into the thousands column $\text{F}$ must be $1$!
  • The Ones Column: $\text{O} + \text{O} = \text{R}$ (plus any carry to the tens). Since $\text{O} + \text{O}$ is even, $\text{R}$ must be an even digit ($0, 2, 4, 6, 8$).
  • The Hundreds Column: $\text{T} + \text{T}$ produced a carry into $\text{F} = 1$. This means $\text{T}$ must be at least $5$ ($\text{T} \ge 5$).
Instead of guessing through hundreds of thousands of combinations by hand, we can state these constraints in Prolog and let its constraint solver deduce the unique solution!
digit(0). digit(1). digit(2). digit(3). digit(4). digit(5). digit(6). digit(7). digit(8). digit(9).
% Leading carry digit into thousands: Replace ???? with 1 F = ???? , digit(O), O \= F, R is (O + O) mod 10, all_different([T, W, O, F, U, R]).

goal: solve(T, W, O, F, U, R).
Move the mouse over a dotted box for more information.

  • Constraint Propagation: By applying the carry rules column-by-column (ones, tens, hundreds) instead of testing all permutations at the end, Prolog prunes the search space by over $99.9\%$, finding the answer in a fraction of a millisecond!
  • Unique Solution: The unique mathematical solution is: $$734 + 734 = 1468$$ with $\text{T}=7, \text{W}=3, \text{O}=4, \text{F}=1, \text{U}=6, \text{R}=8$.

Now you try. Run the code and check that 734 + 734 = 1468.

Type your code here:


See your results here: