Last updated Sep 12, 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 silly things, (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:
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?"
- is a combination.
- is a summation.
- is the floor function.
The answer
The number of hex codes with a sum n can be calculated as follows:
Let's break that down
: Any number of characters k in a hex code, from none of them to all six, can be a digit 1 through 9.
: Those digits can appear in any k of the six positions.
: There are seven choices; 0, A, B, C, D, E, and F; for each of the 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.