Hex color combinatorics

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:

j=0(nk)/s(1)j(kj)(nsj 1k1)

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?"

The answer

The number of hex codes with a sum n can be calculated as follows:

k=06(6k)76kj=0(nk)/9(1)j(kj)(n9j1k1)

Let's break that down

k=06: Any number of characters k in a hex code, from none of them to all six, can be a digit 1 through 9.

(6k): Those digits can appear in any k of the six positions.

76k: There are seven choices; 0, A, B, C, D, E, and F; for each of the 6k 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.