Find Factorial of a Number in C#

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

What you’ll learn

  • What n! means for n ≥ 0, including the surprise rule 0! = 1.
  • A compact recursive solution like the classic homework style, plus an iterative twin that skips deep call stacks.
  • Why ulong still hits a ceiling near 20!, how to guard negatives, and a browser live preview that expands the product.

Overview

Factorial is the everyday “multiply everything from 1 up to n” operation. It looks innocent for tiny n, but answers grow wildly fast — so honest programs also talk about overflow, negative inputs, and when to switch to BigInteger.

Two programs

Recursive and iterative versions both target 5! = 120 with validation.

Live preview

Exact factorials for 0 ≤ n ≤ 20 plus the multiplied-out chain.

Interview realism

Caps for ulong, recursion depth vs loops, and when APIs like BigInteger belong.

Prerequisites

Small C# methods, if, multiplication, and basic for loops.

  • C# basics: using System;, class Program, static void Main(), string interpolation.
  • That integer types have maximum sizes — answers must fit or use a bigger type.

What is factorial?

For an integer n ≥ 0, n! (say “n factorial”) means multiply every whole number from 1 through n. The edge case 0! is defined as 1 — imagine multiplying nothing and agreeing the answer is 1.

Factorials count arrangements: n! different orders exist for n distinct items sitting in a row. They also pop up in algebra and probability.

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

Formal definition

Set 0! = 1. For n ≥ 1, define n! = n · (n-1)!. Equivalently n! = ∏k=1n k, the product of all integers from 1 to n.

5!

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

Quick patterns

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

Takeaway: each step from n to n+1 multiplies the previous factorial by n+1, so digits explode quickly.

Live preview

Exact values for 0 ≤ n ≤ 20, matching what fits in both JavaScript safe integers and a C# ulong demo.

Try 0, 12, or 20. Above 20 we stop printing exact integers here.

Live result
Press “Compute n!” to expand the product and see the value.

Algorithm

Goal: compute n! for nonnegative n inside a type that can hold the answer.

Validate

Reject n < 0 for standard factorial. Optionally bound n so you never overflow your chosen type.

Base case

When n is 0 or 1, answer 1.

Build the product

Either recurse with n · (n-1)! or loop from 2 through n, multiplying into an accumulator.

📜 Pseudocode

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

Recursive factorial

Mirrors the classic reference: CalculateFactorial, returns ulong, sample n = 5. Adds guards for negatives and a safe cap for exact ulong results (20! fits; 21! does not).

c#
using System;

class Program
{
    const int FactorialMaxUlong = 20;

    static ulong CalculateFactorial(int num)
    {
        if (num == 0 || num == 1)
            return 1;

        return (ulong)num * CalculateFactorial(num - 1);
    }

    static void Main()
    {
        int number = 5;

        if (number < 0)
        {
            Console.WriteLine("Factorial is not defined for negative integers here.");
            return;
        }

        if (number > FactorialMaxUlong)
        {
            Console.WriteLine($"n too large for exact ulong in this demo (max {FactorialMaxUlong}).");
            return;
        }

        ulong result = CalculateFactorial(number);
        Console.WriteLine($"Factorial of {number} is: {result}");
    }
}

Explanation

Each call waits on a smaller subproblem until 0 or 1 returns 1; multiplications finish on the way back. Cast num to ulong before multiplying so you stay in unsigned arithmetic.

return (ulong)num * CalculateFactorial(num - 1);

Recurrence. This line is the math rule n! = n × (n-1)! typed directly.

2

Iterative factorial

Same numeric answers with a simple loop — handy when interviewers worry about recursion depth or stack limits.

c#
using System;

class Program
{
    const int FactorialMaxUlong = 20;

    static ulong FactorialIter(int n)
    {
        ulong result = 1;

        for (int i = 2; i <= n; i++)
            result *= (ulong)i;

        return result;
    }

    static void Main()
    {
        int number = 5;

        if (number < 0)
        {
            Console.WriteLine("Factorial is not defined for negative integers here.");
            return;
        }

        if (number > FactorialMaxUlong)
        {
            Console.WriteLine($"n too large for exact ulong in this demo (max {FactorialMaxUlong}).");
            return;
        }

        Console.WriteLine($"Factorial of {number} is: {FactorialIter(number)}");
    }
}

Explanation

Start at 1, multiply by 2, then 3, … up to n. For n equal to 0 or 1, the loop body never runs and result stays 1.

Scaling beyond ulong

BigInteger. System.Numerics.BigInteger can represent enormous factorials exactly at the cost of speed and memory.

Approximation. For statistics you might use logarithms (Math.Log of gamma-related formulas) when only magnitude matters.

Interview: mention overflow first, compare recursion vs loop, then name BigInteger if they push past fixed widths.

❓ FAQ

For a nonnegative integer n, n! means multiply every whole number from 1 through n together. By convention 0! = 1 (think "multiply nothing — we call that 1").
Both 0! and 1! equal 1. Those are base cases that end the rule n! = n × (n-1)! without calling forever.
ulong tops out near 1.8×10^19. Since 21! is bigger than that, this type stores n! exactly only for n up through 20 on typical setups.
Both use about n multiplications. Recursion is short to type but uses call-stack depth O(n). A for-loop keeps extra space O(1) and avoids stack overflow for moderate n that still fit your type.
Standard school factorial is not defined for negative integers. Validate n >= 0 or return an error instead of guessing.
Use System.Numerics.BigInteger or another arbitrary-precision library; fixed-width ulong (or long) will wrap or overflow.
Theta(n) multiplications to build n! exactly with either recursion or a loop; recursion adds Theta(n) stack frames unless tail-call optimized (do not rely on that in interviews).

🔄 Input / output examples

Change number in either program (within 0..20 for exact ulong here). Interactive input might look like int number = int.Parse(Console.ReadLine()); after validation.

nn!
01
11
5120
202432902008176640000

Edge cases and pitfalls

Silent overflow is easy to miss — prefer checks or wider types before shipping homework solutions.

Negative

n < 0

Not standard factorial; print an error or throw instead of returning a bogus positive.

Overflow

21! vs ulong

Too big for ulong; switch to BigInteger or stop with a clear message.

Stack

Deep recursion

Huge n can blow the call stack before arithmetic overflows — another reason interviewers like the loop version.

Types

int results

13! already exceeds 32-bit range — returning int breaks quickly.

⏱️ Time and space complexity

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

Exact factorial needs at least one multiply per new factor; only the hidden stack differs between styles.

Summary

  • Definition: 0! = 1 and n! = n·(n-1)! for n ≥ 1.
  • C#: recursion matches textbooks; iteration trims stack risk; ulong caps near 20!.
  • Next step: learn BigInteger when problems demand bigger answers.
Did you know?

Factorials explode fast: n! multiplies every whole number from 1 to n. A standard ulong can hold exact values only through about 20!; beyond that you need bigger tools such as BigInteger.

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