Recursion and Dynamic Programming
Recursion
Factorial
Compute n! using a recursive definition: 0! = 1, otherwise
n! = n * (n - 1)!. The classic introduction to a self-referential
function.
Algorithm
Canonical input n = 5 finishes after five reductions; the printed
result is 120.
Basic Implementation
basic.sql
.mode list
.headers off
WITH RECURSIVE factorial(n, result) AS (
SELECT 0, 1
UNION ALL
SELECT n + 1, result * (n + 1)
FROM factorial
WHERE n < 5
)
SELECT result FROM factorial WHERE n = 5;
Complexity
- Time: O(n)
- Space: O(n) for the materialized recursive CTE rows
Implementation notes
- SQL: SQLite has no procedural
RETURNvalue, so the recursive definition is unrolled in aWITH RECURSIVE factorial(n, result)CTE. The seed row(0, 1)is the base case; each recursive arm multipliesresultbyn + 1and writes the next row. TheWHERE n < 5guard mirrors the imperative loop bound. - The final projection
SELECT result FROM factorial WHERE n = 5picks the row produced after the last multiplication. Replacing5with another input would reproducen!for that value. - A direct
SELECT exp(SUM(log(...)))would feel clever but lose the educational recursion the lesson is teaching; the explicit CTE keeps each multiplication step visible.
base case
`0! = 1` ends the recursion.
recursive case
`n! = n * (n - 1)!` reduces the input each step until the base case fires.