Hex color combinatorics

Last updated May 7, 2025

The question

How many hexadecimal color codes contain digits that add to a given sum?

I wondered this while playing The Password Game. One of the game's early rules is that the digits in your password must add to 25. Later rules require you to include things that are likely to contain digits, like the hex code of a randomly-chosen color. You can generate a new color as many times as you like, so I wanted to choose a target sum where it wouldn't take too long to refresh until I got a color code with a sum less than or equal to it. I wrote a script to calculate the sum of each color code by brute force (and used the results to decide 5 is a reasonable target sum), but I became curious how I could find the number of codes with a given sum in a more elegant way.

Observations and research

A hex code results from choosing any character from the set \(A=\{\text{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F}\}\) six times. Specifically, the \(16^6=16,777,216\) distinct hex codes can be considered 6-tuples of \(A\), or permutations with repetition of 6 characters from the set.

Since half of math exists because of gambling, I figured thinking of this problem as a dice game would help me find useful information. Indeed, I did find a formula for ways to obtain a given sum of dice rolls, where \(c\) is the number of ways, \(n\) is the sum, \(k\) is the number of dice to roll, and \(s\) is the number of sides per die. (I have renamed some of the variables for consistency.)

\[\begin{equation}c=\sum_{j=0} ^{\lfloor (n-k)/s \rfloor} (-1)^j \binom{k}{j} \binom{n-sj-1}{k-1}\end{equation}\]

Equation (1) does not fully solve the hex code problem. If we apply it to rolling six 16-sided die, it does not account for seven faces having a value of zero: \(B=\{\text{0, A, B, C, D, E, F}\}\). I later found a very similar equation (E, on page 3) that names the problem being solved in more pure-mathematical terms than ways to roll die: the number of \(k\)-compositions of a number \(n\) with each part restricted to a maximum of \(s\).

Making the calculations

Where \(N(n)\) is the number of hex codes with a given sum \(n\), the simplest sum to calculate is \(N(0)\). To have a sum of zero, a hex code must contain only characters from set \(B\), so \(N(0)=7^6\), the number of 6-tuples of \(B\).

For \(n>0\), we apply the rule of product. Choosing a hex code with a sum \(n\) means choosing: