- Expand
5·4·3·2·1
Find Factorial of a Number in C#
What you’ll learn
- What
n!means forn ≥ 0, including the surprise rule0! = 1. - A compact recursive solution like the classic homework style, plus an iterative twin that skips deep call stacks.
- Why
ulongstill hits a ceiling near20!, 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.
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
- 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.
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
function factorial(n): // assume n >= 0
if n <= 1:
return 1
return n * factorial(n - 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).
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.
Iterative factorial
Same numeric answers with a simple loop — handy when interviewers worry about recursion depth or stack limits.
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
🔄 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.
| n | n! |
|---|---|
0 | 1 |
1 | 1 |
5 | 120 |
20 | 2432902008176640000 |
Edge cases and pitfalls
Silent overflow is easy to miss — prefer checks or wider types before shipping homework solutions.
n < 0
Not standard factorial; print an error or throw instead of returning a bogus positive.
21! vs ulong
Too big for ulong; switch to BigInteger or stop with a clear message.
Deep recursion
Huge n can blow the call stack before arithmetic overflows — another reason interviewers like the loop version.
int results
13! already exceeds 32-bit range — returning int breaks quickly.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Recursive | O(n) multiplications | O(n) call frames |
| Iterative | O(n) multiplications | O(1) |
Exact factorial needs at least one multiply per new factor; only the hidden stack differs between styles.
Summary
- Definition:
0! = 1andn! = n·(n-1)!forn ≥ 1. - C#: recursion matches textbooks; iteration trims stack risk;
ulongcaps near20!. - Next step: learn
BigIntegerwhen problems demand bigger answers.
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.
8 people found this page helpful
