Calculate Factorial Using MySQL Stored Function



Following is the example of a stored function that can calculate the factorial of a given number −

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)
Updated on: 2020-06-22T08:03:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements