We would like to define a formula that returns the nth hexadecimal digit of π. A few manipulations are required to implement a spigot algorithm using this formula.
We must first rewrite the formula as:
Now, for a particular value of n and taking the first sum, we split the sum to infinity across the nth term:
We now multiply by 16n, so that the hexadecimal point (the divide between fractional and integer parts of the number) is in the nth place:
Since we only care about the fractional part of the sum, we look at our two terms and realise that only the first sum is able to produce whole numbers; conversely, the second sum cannot produce whole numbers, since the numerator can never be larger than the denominator for k > n. Therefore, we need a trick to remove the whole numbers for the first sum. That trick is to reduce modulo 8k + 1. Our sum for the first fractional part then becomes:
Notice how the modulus operator always guarantees that only the fractional sum will be kept. To calculate 16n−k mod (8k + 1) quickly and efficiently, the modular exponentiation algorithm is done at the same loop level, not nested. When its running 16x product becomes greater than one, the modulus is taken, just as for the running total in each sum.
Now to complete the calculation, this must be applied to each of the four sums in turn. Once this is done, the four summations are put back into the sum to π:
Since only the fractional part is accurate, extracting the wanted digit requires that one removes the integer part of the final sum and multiplies by 16 to "skim off" the hexadecimal digit at this position (in theory, the next few digits up to the accuracy of the calculations used would also be accurate).
This process is similar to performing long multiplication, but only having to perform the summation of some middle columns. While there are some carries that are not counted, computers usually perform arithmetic for many bits (32 or 64) and round, and we are only interested in the most significant digit(s). There is a possibility that a particular computation will be akin to failing to add a small number (e.g. 1) to the number 999999999999999, and that the error will propagate to the most significant digit.