factorial() 是一个返回所提供整数阶乘的系统函数。
factorial() 在 PostgreSQL 7.0 中添加。
用法
factorial ( bigint ) → numeric
变更历史
- PostgreSQL 14
- 不允许负数阶乘(提交 0a40563e)
- PostgreSQL 8.0
- PostgreSQL 7.0
- 添加(提交 64568100)
示例
factorial() 的用法示例
postgres=# SELECT x, factorial(x) FROM generate_series(0,10) AS x; x | factorial ----+----------- 0 | 1 1 | 1 2 | 2 3 | 6 4 | 24 5 | 120 6 | 720 7 | 5040 8 | 40320 9 | 362880 10 | 3628800 (11 rows)
尝试获取负数的阶乘(PostgreSQL 14 及更高版本)
postgres=# SELECT factorial(-1); ERROR: factorial of a negative number is undefined
请注意,在 PostgreSQL 13 及更早版本中,该函数将错误地返回 1
postgres=# SELECT factorial(-1);
factorial
-----------
1
(1 row)
参考资料
- PostgreSQL 文档: 数学函数
