如何编写计算给定数字阶乘的 MySQL 存储函数?


以下是存储函数示例,该函数可计算给定数字的阶乘 -

CREATE FUNCTION factorial (n DECIMAL(3,0))
RETURNS DECIMAL(20,0)
DETERMINISTIC
BEGIN
DECLARE factorial DECIMAL(20,0) DEFAULT 1;
DECLARE counter DECIMAL(3,0);
SET counter = n;
factorial_loop: REPEAT
SET factorial = factorial * counter;
SET counter = counter - 1;
UNTIL counter = 1
END REPEAT;
RETURN factorial;
END //

mysql> Select Factorial(5)//
+--------------+
| Factorial(5) |
+--------------+
|          120 |
+--------------+
1 row in set (0.27 sec)

mysql> Select Factorial(6)//
+--------------+
| Factorial(6) |
+--------------+
|          720 |
+--------------+
1 row in set (0.00 sec)

更新于:22-06-2020

超过 1 千次浏览

开启 职业生涯

完成课程获得认证

开始学习
广告