This website is for reference purposes only. Users are responsible for any misuse. The owner is not liable for any consequences.
Back to Database Management Systems (Laboratory)
5.1.7HardCODE

Fact Function to find Factorial

Question

Solution

SQL

CREATE OR REPLACE FUNCTION fact(n INTEGER)
RETURNS INTEGER AS $$
DECLARE
	b INTEGER := 1;
	i INTEGER;
BEGIN
	IF n < 0 THEN
		RAISE EXCEPTION 'Factorial is not defined for negative numbers';
	END IF;

	FOR i IN 1..n LOOP
		b := b * i;
	END LOOP;

	RETURN b;
END;

$$ LANGUAGE plpgsql;


2/2 test cases passed

4/4 hidden test cases passed