how to get the value of an integer x
, indicated by x!
, it is the product of the numbers 1 to x.
Example: 5! 1x2x3x4x5 = 120.
>
This is the optimal implementation in size and speed:
int factorial(int x)
{
static const int f[13] = { 1, 1, 2, 6, 24, 120, /* ... */ };
if ((unsigned)x < (sizeof f/sizeof f[0])) return f[x];
else return INT_MAX+1; /* or your favorite undefined behavior */
}
Hint: x!
(x
factorial) does not fit in an int except for very very small values of x
.