data-structures · beginner · ~15 min

Recursive factorial

Compute n! with a base case and a self-call.

Challenge

Implement:

long long factorial(int n);

Return n! computed recursively. factorial(0)=1. 0 <= n <= 20.

Input format

n in [0,20].

Output format

n!.

Constraints

Use long long (20! overflows 32 bits).

Starter code

#include <stddef.h>
/* n! computed recursively. 0<=n<=20. factorial(0)=1. */
long long factorial(int n){ (void)n; return 0; }

Common mistakes

Missing base case (infinite recursion); recursing without multiplying by n.

Edge cases to handle

0! and 1! are both 1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.