Skip to main content

Factorial Calculator

Computes the factorial of a non-negative integer

Problem Overview

📐 The Mathematical Building Block
Factorial computation is a cornerstone of combinatorics, probability, and algorithmic thinking! Calculate n! (n factorial) which represents the number of ways to arrange n distinct objects.

🔢 The Mathematical Concept:

  • Definition: n! = n × (n-1) × (n-2) × ... × 1
  • Base Cases: 0! = 1, 1! = 1 (mathematical convention)
  • Growth Rate: Extremely fast - 10! = 3.6 million, 20! = 2.4 quintillion!
  • Edge Cases: Only defined for non-negative integers
  • Two Classic Approaches:
  • Recursive: Elegant mathematical definition, n × factorial(n-1)
  • Iterative: Space-efficient loop, better for large values
  • Real-World Applications:
  • Combinatorics: Permutations, arrangements, and ordering problems
  • Probability: Calculating possible outcomes in statistics
  • Algorithms: Dynamic programming and memoization examples
  • Cryptography: Key generation and mathematical security proofs
💡 Learning Value:
  • Recursion vs iteration trade-offs (space vs readability)
  • Input validation and edge case handling
  • Mathematical algorithm implementation
  • Stack overflow risks with deep recursion

Concepts

recursioniterationinput validationmathematics

Complexity Analysis

Time:O(n)
Space:O(n) for recursive, O(1) for iterative
Performance Notes:

- Time: O(n) - must multiply n numbers - Space: O(n) recursive call stack, O(1) iterative approach

Solutions

factorial

Time: O(n) | Space: O(n)
export function factorial(n: number): number {
  if (!Number.isInteger(n)) throw new Error("Input must be an integer");
  if (n < 0) throw new Error("Factorial is not defined for negative numbers");
  if (n === 0 || n === 1) return 1;
  return n * factorial(n - 1);
}

Examples & Test Cases

#1Factorial of 5
Input:5
Output:120
#2Factorial of 0
Input:0
Output:1
#3Factorial of 1
Input:1
Output:1
#4Factorial of 3
Input:3
Output:6
#5Negative error
Input:-1
Output:{}
#6Non-integer error
Input:2.5
Output:{}