Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F407 · level intermediate · 11 min read
Open in the interactive handbook

76а. Factorial on a microcontroller: recursion and loop, overflow, big numbers, gamma and logarithm, table

In section 76 the factorial appeared only once: in 76.6 the binomial coefficient cannot be computed through n! — the intermediate values do not fit in an int. Here the factorial is taken apart in full, because it shows several things at once that matter for firmware: how much stack recursion eats and what the compiler does with it, where each type ends, when a table in flash memory beats computation, how to compute 1000! without libraries and what it costs on a Cortex-M4, what replaces n! when only its order is needed, and why Taylor series do not divide by the factorial.

Basis: one file fact76a.c built with gcc 12.2.0 on the computer (stm-sys:1) and arm-none-eabi-gcc 12.2.1 for the Cortex-M4F; the firmware ran in QEMU 7.2 (stm-arm:1, board netduinoplus2 with an STM32F405 — the same core as the F407). QEMU with -icount counts instructions, not cycles: the time in this section is a lower bound. The STM32F407 clock comes from the device description in the Keil pack STM32F4xx_DFP 2.17.1. All numbers come from the saved run fact76a_host.txt.

Terms used in the documentation

Original Meaning
factorial n! factorial: 1 · 2 · … · n, 0! = 1
recursion, tail call recursion, tail call: the call is the last action of the function
stack frame stack frame: return address, saved registers, local variables
-fstack-usage gcc option: frame size of each function in a .su file
overflow builtins gcc built-in functions for multiplication with an overflow check
lookup table table of ready values
arbitrary-precision arithmetic long arithmetic: a number in an array of limbs
Stirling's formula Stirling's formula: n! approximated through a power and a root
gamma function Γ, lgamma, tgamma gamma function, Γ(n + 1) = n!; its logarithm and value in libm
Taylor series Taylor series
Horner's scheme Horner's scheme: a polynomial as a chain of "multiply and add"

76а.1 What the factorial is and where it appears in firmware

n! is the product of all integers from 1 to n, by definition 0! = 1. It grows faster than any power: 10! = 3 628 800, 20! already has 19 digits.

In firmware the factorial is rarely needed by itself, but it stands behind many formulas:

Where What the factorial does there
Taylor series for sin, cos, exp divisors 1/3!, 1/5!, … of the series terms
combinations C(n, k) n!/(k!(n − k)!) — but it must not be computed through factorials (76.6)
probabilities binomial and Poisson distributions, false-alarm estimates
permutations how many orders n events have, the index of a permutation in a table
tests n! mod p and the number of trailing zeros — short check numbers

Hence the plan: first how to compute it (76а.2), where the types end (76а.3), table and series (76а.4), long numbers (76а.5), logarithm and gamma (76а.6).


76а.2 Recursion versus loop: the stack and what gcc -O2 does

Three ways to write the same thing:

uint64_t fact_rec(unsigned n)
{
    if (n < 2)
        return 1;
    return n * fact_rec(n - 1);
}
uint64_t fact_loop(unsigned n)
{
    uint64_t r = 1;
    for (unsigned i = 2; i <= n; i++)
        r *= i;
    return r;
}
static uint64_t fact_acc(unsigned n, uint64_t acc)
{
    if (n < 2)
        return acc;
    return fact_acc(n - 1, acc * n); /* хвостовой вызов */
}

On the computer all three and the table from 76а.4 gave the same answers for n from 0 to 20. The difference is in the stack and the instructions. The -fstack-usage option writes the frame size of each function into a .su file; the real depth was measured in QEMU: the area below the stack pointer was filled with the pattern 0xA5A5A5A5, the function was called and the lowest touched word was searched for.

frame by .su, -O0 stack at n = 20, -O0 frame by .su, -O2 stack at n = 20, -O2 instructions per call, -O0 / -O2
fact_rec 32 bytes 636 bytes 4 bytes 4 bytes 588 / 180
fact_tail → fact_acc 40 bytes 816 bytes 4 bytes 4 bytes 677 / 180
fact_loop 40 bytes 36 bytes 0 bytes 0 bytes 440 / 122

Without optimisation recursion honestly puts a frame on every level: at n = 10 fact_rec ate 316 bytes, at n = 20 — 636, 32 bytes per level. For the factorial this is a trifle, but the same scheme in parsing nested expressions or walking a tree ends in a stack overflow (11.4).

With -O2 gcc 12 turned both recursions into a loop: in the machine code not a single call of fact_rec or fact_acc remained (at -O0 — one each), the stack is 4 bytes for any n. Replacing a tail call with a jump is a common technique, but gcc also unrolled n * fact_rec(n - 1), where the multiplication comes after the call: multiplication can be reordered. Do not rely on it: at -O0 the recursion stays, and the C standard does not promise tail calls. In firmware write the loop — it is shorter even at -O2: 122 instructions against 180.

Instruction counts are per call at n = 20, without the 4 instructions of the measuring loop itself.


76а.3 Overflow: where each type ends

The largest n whose n! still fits was found by a run — on the computer and in QEMU the answers are the same:

Type Type limit Largest n!
uint32_t 4.29·10⁹ 12! = 479 001 600
int32_t 2.15·10⁹ 12!
uint64_t 1.84·10¹⁹ 20! = 2 432 902 008 176 640 000
float 3.40·10³⁸ 34! ≈ 2.952328·10³⁸
double 1.80·10³⁰⁸ 170! ≈ 7.257416·10³⁰⁶

Growth of n! on a logarithmic scale: on the left n from 0 to 40, on the right up to 180; horizontal dashed lines are the limits of uint32_t, uint64_t, float and double, vertical ones are the largest n whose n! still fits: 12, 20, 34 and 170; 100! has 158 digits, 1000! has 2568 digits

float holds 34!, but exactly — only up to 13!: the 24-bit mantissa runs out of bits after that, and (float)14! already differs from the integer 14!. double is exact up to and including 20! — after that uint64_t ends anyway. So "float up to 34!" is about the order of magnitude, not the exact value.

What happens past the limit. For unsigned types overflow is defined — counting modulo 2³² (122.4): 13! in a uint32_t silently gives 1 932 053 504 instead of 6 227 020 800. For a signed int it is undefined behaviour (123.3): the compiler may throw away a check written after the multiplication. The check must come before or together with the operation — gcc and clang have a built-in function for this:

int fact_u32(unsigned n, uint32_t *out)
{
    uint32_t r = 1;
    for (unsigned i = 2; i <= n; i++)
        if (__builtin_mul_overflow(r, i, &r))
            return 0;
    *out = r;
    return 1;
}

fact_u32(13, …) returned 0. On a Cortex-M4 the check is almost free: the multiplication umull gives the high word, and that is what is compared with zero. At -O2 a call for n = 12 is 75 instructions, the function is 52 bytes.


76а.4 A table in flash memory, Taylor series and ready 1/n!

Since only 13 values fit in a uint32_t, it is simpler to store them:

static const uint32_t FACT_TAB[13] = {
    1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600,
};
uint32_t fact_tab(unsigned n)
{
    return n < 13 ? FACT_TAB[n] : 0; /* 0 — не помещается в uint32_t */
}
-O2, Cortex-M4 code bytes data bytes instructions per call
fact_tab + FACT_TAB 20 52 7
fact_u32 (loop with check), n = 12 52 0 75
fact_loop (uint64_t), n = 20 36 0 122

The table is 36 bytes larger than the fact_loop loop and more than 10 times faster than fact_u32. For uint64_t a table of 21 values takes 168 bytes — also little. Computing n! in firmware makes sense only if n is large and the answer is needed as a long number (76а.5) or as a logarithm (76а.6).

Taylor series. sin x = x − x³/3! + x⁵/5! − … The naive version computes the power and the factorial anew for every term:

float t = powf(x, (float)n) / (float)fact_loop(n);

The right way is to store ready coefficients ±1/n! and evaluate the polynomial by Horner's scheme: x · (c₁ + x² · (c₃ + x² · (c₅ + …))). Not a single division, not a single power:

float sin_horner(float x)
{
    float x2 = x * x;
    float p = SIN_C[6];
    for (int k = 5; k >= 0; k--)
        p = p * x2 + SIN_C[k];
    return p * x;
}

Both versions have 7 terms, up to x¹³/13!. Their accuracy is the same: the largest error on [−π, π] is 2.12·10⁻⁵ and 2.11·10⁻⁵, this is the tail of the series, not rounding. The cost differs: on a Cortex-M4F at -O2 the naive call is 2238 instructions, Horner is 26, 86 times fewer. sinf from newlib is 92 instructions. In the machine code of the naive version every term has a call to powf, a conversion of uint64_t to float through __aeabi_ul2f and a vdiv.f32 division; Horner has none of the three; the coefficients are computed once — on the computer, when the table is written.


76а.5 Big numbers: 100! and 1000! in an array of limbs

When the exact n! beyond 20! is needed, the number is kept in an array. A convenient base is 10⁹: a limb fits in a uint32_t, the product of a limb by n plus the carry fits in a uint64_t, and decimal output is simply 9 digits per limb.

for (unsigned k = 0; k < len; k++) {
    uint64_t t = (uint64_t)d[k] * i + carry;
    d[k] = (uint32_t)(t % BIG_BASE);
    carry = (uint32_t)(t / BIG_BASE);
}
limbs digits instructions, -O2 time at 168 MHz, at least
100! 18 158 49 428 0.29 ms
1000! 286 2568 7.88 million 47 ms

1000! needs an array of 286 limbs — 1144 bytes of RAM. Without optimisation 1000! takes 20.99 million instructions. The main cost is the 64-bit division by 10⁹: the Cortex-M4 has no such instruction, and % and / go to the library __aeabi_uldivmod. The top limb of 1000! is 402, the whole number starts with 402…

Two short characteristics of n! are computed without long numbers at all:

unsigned fact_zeros(unsigned n)
{
    unsigned z = 0;
    while (n) {
        n /= 5;
        z += n;
    }
    return z;
}

76а.6 The logarithm of the factorial: Stirling, lgamma and tgamma

Often what is needed is not n! itself but its order — in probabilities, in estimating the number of variants, in ratios of factorials. Then ln n! is computed: it grows slowly and does not overflow. The gamma function extends the factorial to fractional numbers: Γ(n + 1) = n!. libm has lgamma (the logarithm) and tgamma (the value itself). ln 1000! = 5912.128178, hence the number of digits of 1000! is ⌊5912.128178 / ln 10⌋ + 1 = 2568, the same as for the long number.

Stirling's formula: ln n! ≈ n ln n − n + ½ ln(2πn). With the correction +1/(12n) it is orders of magnitude more accurate:

n Stirling error with the 1/(12n) correction
1 7.8 % 0.23 %
10 0.83 % 2.8·10⁻⁶
100 0.083 % 2.8·10⁻⁹

Without the correction Stirling underestimates n! by about 1/(12n) — exactly what the correction gives back.

Cost on a Cortex-M4F (QEMU, instructions per call):

Function Argument Instructions
lgammaf (float) 100 139
tgammaf (float) 5.5 234
lgamma (double) 100 3970

On the M4F float is computed by the FPU, double in software, hence the 29-fold difference. The accuracy of lgammaf for n from 2 to 1000 — relative error at most 1.33·10⁻⁷, that is at the level of float itself. tgammaf(36) = 35! is already infinity — the same limits as in 76а.3. For firmware the conclusion is simple: the order of n! — through lgammaf, not through double.


76а.7 Pitfalls

A recursive factorial works in the release build and crashes in the debug build. At -O2 gcc made a loop out of the recursion, at -O0 every level costs 32 bytes of stack. For n = 20 this is 636 bytes, and for a recursive walk of something bigger — a stack overflow that does not exist in the release version. Write a loop.

int for the factorial silently lies from 13! on. 13! does not fit in 32 bits. An unsigned type gives the remainder modulo 2³², a signed one gives undefined behaviour (123.3). The check is __builtin_mul_overflow or a table with a bound.

"float holds 34!" is not the same as "float computes 34! exactly". Exactly — only up to 13!. For combinations and probabilities this usually does not matter, for checksums it does.

Dividing by the factorial in every term of a series. The same sin is 86 times more expensive than by Horner with ready coefficients, at the same accuracy.

double functions of libm on an M4F. lgamma is 29 times more expensive than lgammaf: the Cortex-M4 FPU has single precision only.

The stack measurement is spoiled by an interrupt. The first depth measurement in QEMU showed 104 bytes for a function with a 4-byte frame: SysTick fired after being re-enabled, and the interrupt frame with the FPU registers — those very 104 bytes — landed in the pattern-filled area. The pattern is checked with interrupts off.


76а.8 Summary

Next: section 76б "Sorting on a microcontroller: insertion, Shell, quicksort without recursion, merge and an ADC median filter" — which sort to take with 2 KB of RAM and a predictable-time requirement, and how an ADC median filter works.

Open in the interactive handbook