Find Factorial in C

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Recursion & loop

What you’ll learn

  • The definition of n! for n ≥ 0, including 0! = 1.
  • A recursive solution matching the classic interview style, plus an iterative equivalent.
  • Overflow limits for unsigned long long, input validation, and a small live preview.

Overview

Factorial grows faster than any exponential. A correct small-n program is easy; a robust one also checks n ≥ 0, watches overflow, and picks recursion or a loop based on constraints.

Two programs

Recursive (5! = 120) and iterative with the same result.

Live preview

Exact integers for 0 ≤ n ≤ 20 in this widget (fits unsigned long long and JS safe integers).

Rigor

Guards for negative inputs and 21+ overflow on 64-bit unsigned long long.

Prerequisites

Functions, if, multiplication, and optional for loops.

  • #include <stdio.h>, int main(void), printf with %llu for wide unsigned results.
  • Awareness that fixed-width integers wrap on overflow in C unsigned arithmetic.

What is factorial?

For an integer n ≥ 0, n! is the product of every integer from 1 through n. When n = 0, that is the empty product, defined as 1, so 0! = 1.

Factorials count permutations: n! is the number of ways to order n distinct objects. They appear in Taylor series, binomial coefficients, and probability.

5! 120
Recurrence n! = n·(n-1)!
0! 1

Formal definition

Define 0! = 1 and, for n ≥ 1, n! = n · (n-1)!. Equivalently n! = ∏k=1n k.

5!

5 × 4 × 3 × 2 × 1 = 120.

Intuition

5! 120
Expand
5·4·3·2·1
6! 720
Step
6 · 5!

Takeaway: each increment of n multiplies the previous factorial by n, which is why values explode in size.

Live preview

Exact factorial for 0 ≤ n ≤ 20 (matches a typical unsigned long long ceiling before wrap).

Try 0, 12, or 20. Values above 20 are not shown exactly here.

Live result
Press “Compute n!”.

Algorithm

Goal: compute n! for nonnegative n within a chosen numeric type.

Base case

If n ≤ 1, return 1 (covers 0! and 1!).

Recurrence or loop

Otherwise multiply n by (n-1)!, or initialize result = 1 and absorb factors 2..n in a loop.

📜 Pseudocode

Pseudocode
function factorial(n):  // assume n >= 0
    if n <= 1:
        return 1
    return n * factorial(n - 1)
1

Recursive factorial

Same idea as the reference (calculateFactorial there): recursion, number = 5, and %llu output. Renamed to calculate_factorial here, with a safe upper bound for unsigned long long on 64-bit targets.

c
#include <stdio.h>

#define FACT_MAX_ULL 20

unsigned long long calculate_factorial(int num) {
    if (num == 0 || num == 1) {
        return 1u;
    }
    return (unsigned long long)num * calculate_factorial(num - 1);
}

int main(void) {
    int number = 5;

    if (number < 0) {
        printf("Factorial is not defined for negative integers here.\n");
        return 0;
    }
    if (number > FACT_MAX_ULL) {
        printf("n too large for exact unsigned long long in this demo (max %d).\n", FACT_MAX_ULL);
        return 0;
    }

    unsigned long long result = calculate_factorial(number);
    printf("Factorial of %d is: %llu\n", number, result);

    return 0;
}

Explanation

Each call shrinks num until the base case; the products bubble back up. Cast num before multiplying so intermediate products stay in unsigned long long.

2

Iterative factorial

Same numeric result for n = 5, with O(1) auxiliary space and no call-stack depth proportional to n.

c
#include <stdio.h>

#define FACT_MAX_ULL 20

unsigned long long factorial_iter(int n) {
    unsigned long long r = 1u;
    int i;

    for (i = 2; i <= n; ++i) {
        r *= (unsigned long long)i;
    }
    return r;
}

int main(void) {
    int number = 5;

    if (number < 0) {
        printf("Factorial is not defined for negative integers here.\n");
        return 0;
    }
    if (number > FACT_MAX_ULL) {
        printf("n too large for exact unsigned long long in this demo (max %d).\n", FACT_MAX_ULL);
        return 0;
    }

    printf("Factorial of %d is: %llu\n", number, factorial_iter(number));
    return 0;
}

Explanation

The loop multiplies 1 by every integer from 2 through n. For n in {0,1}, the loop body never runs and r stays 1.

Optimization and scaling

Bigger values. Use arbitrary-precision libraries (GMP), logarithms of gamma for floating approximations, or prime-factor exponent tables for exact huge factorials—not a widening long long alone.

Prime swing / split recursion. Advanced algorithms reduce the number of large multiplications; overkill for basic interviews.

Interview: state overflow, validate n ≥ 0, and compare recursion depth vs loop.

❓ FAQ

For a nonnegative integer n, n! is the product of all integers from 1 through n. By definition, 0! = 1 (empty product).
Both 0! and 1! equal 1. Those cases terminate the recurrence n! = n * (n-1)! without further calls.
On typical 64-bit platforms, unsigned long long holds values up to 2^64-1. Since 21! exceeds that, this type can store n! exactly only for n <= 20 in the usual range.
Both run O(n) multiplications. Recursion uses O(n) call stack space; a simple loop uses O(1) extra space and avoids stack overflow for moderately large n (still subject to numeric overflow).
Factorial is not defined for negative integers in the standard combinatorial sense. Programs should validate n >= 0 before computing.
Computing n! with n multiplications costs O(n) time. Space is O(n) for naive recursion depth or O(1) for an iterative loop excluding the result width.

🔄 Input / output examples

Change number in either example (within 0..20 for exact unsigned long long here).

nn!
01
11
5120
202432902008176640000

Edge cases and pitfalls

Unsigned overflow is silent in C; always bound n or check products against limits before they wrap.

Negative

n < 0

Not the standard factorial; reject or map to an error code instead of recursing.

Overflow

21! and beyond

Exceeds 2^64-1; widen to big integers or reduce the problem (e.g. trailing zeros modulo).

Stack

Deep recursion

Even when n fits in a type, very large n can overflow the call stack before the integer does.

Types

int result

13! already exceeds 32-bit int; prefer wide unsigned for small-n exact factorials.

⏱️ Time and space complexity

VersionTimeExtra space
RecursiveO(n) multiplicationsO(n) call frames
IterativeO(n) multiplicationsO(1)

Both approaches use Θ(n) arithmetic operations for exact n!; only the hidden stack differs.

Summary

  • Definition: 0! = 1 and n! = n·(n-1)! for n ≥ 1.
  • Code: recursion matches the classic template; iteration saves stack depth.
  • Watch-outs: negatives undefined, unsigned long long caps near 20!, silent unsigned wrap.
Did you know?

Stirling's approximation describes how fast n! grows: asymptotically n! ∼ √(2πn) · (n/e)n. It is standard in analysis even when the exact integer no longer fits in fixed-width types.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful