Last updated Aug 24, 2025
The question
Given a sum \(n\), how many hexadecimal color codes are there with digits that add to \(n\)?
I wondered this while writing about strategies for The Password Game. You win by creating a password that, among other absurd requirements, (a) includes the hex code of a randomly chosen color and (b) has digits that add to 25, no more and no less. Since you can get a new random color as many times as you want, I wanted to estimate how long it would take to find one that kept the sum of digits below 25. I wrote a script to simulate the problem and got a good estimate that way, but I noticed there was a pattern to how likely it was for a hex code to have any given sum, and became curious about what that pattern was.
Background & research
Since combinatorics problems often use gambling as an example, I tried thinking of my question in terms of a game where I roll six die, representing the six characters in a hex code. Indeed, a formula has been found for the number of ways to get \(n\) points on a dice roll, where \(k\) is the number of dice and \(s\) is the number of sides per die:
\[∑↙{j=0}↖{⌊(n-k)/s⌋} (-1)^j \binom{k}{j} \binom{n-sj-1}{k-1}\]
I later learned that generically, this is a formula for compositions: the number of sequences of \(k\) integers 1 through \(s\) that add to \(n\).
"Wait, what do those symbols mean?"
- \(\binom{n}{k}\) is a combination.
- \(\∑↙{n=0}↖{k} n\) is a summation.
- \(⌊n⌋\) is the floor function.
The answer
The number of hex codes with a sum \(n\) can be calculated as follows:
\[∑↙{k=0}↖{6} \binom{6}{k} 7^{6-k} ∑↙{j=0}↖{⌊(n-k)/9⌋} (-1)^j \binom{k}{j} \binom{n-9j-1}{k-1} \]
Let's break that down
\(∑↙{k=0}↖{6}\): Any number of characters \(k\) in a hex code, from none of them to all six, can be a digit 1 through 9.
\(\binom{6}{k}\): Those digits can appear in any \(k\) of the six positions.
\(7^{6-k}\): There are seven choices; 0, A, B, C, D, E, and F; for each of the \(6-k\) remaining characters.
We know the rest gives us the number of sequences of \(k\) non-zero digits that add up to \(n\). To understand why, we can use the stars and bars method.