Howto compute the factorial of x

前端 未结 7 1344
一生所求
一生所求 2020-12-20 00:05

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.

7条回答
  •  时光说笑
    2020-12-20 00:07

    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.

提交回复
热议问题