Writing a Recursive PostgreSQL Function for Factorial Calculation
Function to Calculate Factorial of a Number
Write a PostgreSQL function to calculate the factorial of a given integer.
Solution:
-- Create a function named factorial that takes an integer as input and returns a big integer
CREATE FUNCTION factorial(n INT) RETURNS BIGINT AS $$
BEGIN
-- Base case: if n is 0, return 1
IF n = 0 THEN
RETURN 1;
ELSE
-- Recursive case: return n multiplied by the factorial of (n - 1)
RETURN n * factorial(n - 1);
END IF;
END;
-- Specify the language used in the function as PL/pgSQL
$$ LANGUAGE plpgsql;
Explanation:
- Purpose of the Query:
- Calculates the factorial of a given number recursively.
- Key Components:
- Uses recursion to compute factorial values
- Real-World Application:
- Used in probability theory, statistical models, and computing permutations.
For more Practice: Solve these Related Problems:
- Write a PostgreSQL function to calculate the sum of all numbers from 1 to N.
- Write a PostgreSQL function to compute the Fibonacci sequence up to a given number.
- Write a PostgreSQL function that finds the factorial of a number using a loop instead of recursion.
- Write a PostgreSQL function that calculates the factorial but returns NULL if the input is negative.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous PostgreSQL Exercise: Function to Check if a Number is Even or Odd.
Next PostgreSQL Exercise: Function to Count Employees in a Department.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics