Permutation & Combination Calculator

Compute permutations nPr (order matters) and combinations nCr (order does not matter) with factorial derivations.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Instant Computation • 100% Client-Side Privacy • Exact Mathematical Precision
Loading tool engine...
Frequently Used With:Scientific Calculator →Percentage Calculator →Smart Basic Calculator with Audit Tape →Fraction & Mixed Number Calculator →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.

Architectural and Mathematical Foundations of Combinatorics

Combinatorics is the foundational discipline of discrete mathematics focused on the enumeration, arrangement, and structural grouping of elements within defined finite sets. In computer science, cryptography, statistical mechanics, and quantitative finance, combinatorial calculations determine state-space sizes, probability densities, entropy metrics, and algorithmic time complexity.

The fundamental dichotomy governing combinatorial problems is twofold:

  1. Ordering Requirement: Does the sequential arrangement of selected elements define a unique outcome?
  2. Repetition Constraint: Can an element be selected more than once (sampling with replacement), or is each element consumed upon selection (sampling without replacement)?

Understanding this four-quadrant space is essential before selecting an algebraic model:

Selection TypeOrder Matters (Permutation)Order Does Not Matter (Combination)
Without ReplacementSimple Permutation: $P(n, r) = \frac{n!}{(n - r)!}$Simple Combination: $C(n, r) = \binom{n}{r} = \frac{n!}{r!(n - r)!}$
With ReplacementPermutation with Repetition: $n^r$Combination with Repetition (Stars & Bars): $\binom{n + r - 1}{r}$

Exhaustive Mathematical Formulations and Derivations

1. Fundamental Counting Principle

If an operation can be performed in $n_1$ ways, and a subsequent independent operation can be performed in $n_2$ ways, and a $k$-th operation in $n_k$ ways, the total number of composite configurations is given by the product:

$$N = \prod_{i=1}^{k} n_i = n_1 \times n_2 \times \dots \times n_k$$

2. Permutations Without Replacement ($nPr$)

When selecting $r$ distinct items from a pool of $n$ available items where sequence is significant, the first item has $n$ possibilities, the second has $n-1$, continuing down to the $r$-th item with $n - (r - 1)$ possibilities:

$$P(n, r) = n(n-1)(n-2)\dots(n-r+1) = \frac{n!}{(n - r)!}$$

Where $n!$ (n factorial) represents: $$n! = \prod_{i=1}^{n} i = n \times (n - 1) \times (n - 2) \times \dots \times 2 \times 1$$ By mathematical convention derived from the Gamma function $\Gamma(n) = (n-1)!$, $0! = 1$.

3. Combinations Without Replacement ($nCr$)

When the order of the $r$ selected items does not produce a distinct configuration, every group of $r$ elements can be arranged in $r!$ internal permutations. To eliminate duplicate groupings from $P(n, r)$, we divide by $r!$:

$$C(n, r) = \binom{n}{r} = \frac{P(n, r)}{r!} = \frac{n!}{r!(n - r)!}$$

Algebraic Symmetry Property

Because choosing $r$ elements to include from a set of size $n$ is mathematically equivalent to choosing $n - r$ elements to exclude:

$$\binom{n}{r} = \binom{n}{n - r}$$

This property halves the computational iterations required when evaluating large values of $r$, because one can always choose $\min(r, n - r)$.

4. Permutations with Identical Elements (Multiset Permutations)

When arranging an entire set of $n$ items containing subsets of indistinguishable elements of sizes $n_1, n_2, \dots, n_k$ such that $\sum_{i=1}^k n_i = n$:

$$P_{\text{multiset}} = \frac{n!}{n_1! , n_2! , \dots , n_k!}$$

This formulation resolves anagram generation (for example, finding the total distinct letter arrangements of the word "MISSISSIPPI" where $n=11, n_M=1, n_I=4, n_S=4, n_P=2$).

5. Combinations with Repetition (Stars and Bars Theorem)

When selecting $r$ items from $n$ categories where items may be repeatedly selected and order is irrelevant, the problem maps onto distributing $r$ identical items ("stars") across $n$ distinct categories separated by $n - 1$ dividers ("bars"). The total number of positions is $r + n - 1$:

$$\left(!\binom{n}{r}!\right) = \binom{n + r - 1}{r} = \frac{(n + r - 1)!}{r!(n - 1)!}$$

6. Circular Permutations

Arranging $n$ distinct items along a fixed circle removes the linear starting reference point. Rotating all items by any position results in an identical relative arrangement:

  • Asymmetric Circular Permutations (fixed orientation, such as seating around a dinner table): $$P_{\text{circle}} = \frac{n!}{n} = (n - 1)!$$
  • Symmetric Circular Permutations (reversible orientation where flipping the loop preserves identity, such as keys on a ring or beads on a necklace): $$P_{\text{necklace}} = \frac{(n - 1)!}{2}$$

Important Algebraic Identities and Series

Combinatorial coefficients form the foundational building blocks of discrete analysis and polynomial expansions:

Pascal's Recurrence Identity

$$\binom{n}{k} = \binom{n - 1}{k - 1} + \binom{n - 1}{k}$$ This identity proves that any binomial coefficient is the sum of the two coefficients directly above it in Pascal's Triangle, allowing exact integer computation without division.

The Binomial Theorem

$$(x + y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n - k} y^k$$ Setting $x = 1$ and $y = 1$ demonstrates that the total number of possible subsets of an $n$-element power set is: $$\sum_{k=0}^{n} \binom{n}{k} = 2^n$$

Vandermonde's Identity

$$\binom{m + n}{r} = \sum_{k=0}^{r} \binom{m}{k} \binom{n}{r - k}$$

Stirling's Asymptotic Approximation

When evaluating factorials for large values of $n$ ($n > 100$) where direct multiplication causes hardware overflow, Stirling's formula provides high-precision approximations: $$n! \sim \sqrt{2 \pi n} \left(\frac{n}{e}\right)^n \left(1 + \frac{1}{12n} + \frac{1}{288n^2} - \dots\right)$$ In logarithmic space: $$\ln(n!) \approx n \ln(n) - n + \frac{1}{2} \ln(2\pi n)$$


Computational Limitations and Numerical Stability

A primary challenge in engineering combinatorial software is avoiding arithmetic overflow. Standard hardware primitives experience rapid overflow:

  • A 32-bit unsigned integer overflows at $13!$ ($13! = 6,227,020,800 > 2^{32} - 1$).
  • A 64-bit unsigned integer overflows at $21!$ ($21! \approx 5.109 \times 10^{19} > 2^{64} - 1$).
  • Standard IEEE-754 double-precision floating-point numbers (64-bit) overflow to Infinity at $171!$ ($170! \approx 7.257 \times 10^{306}$).

Multiplicative Cancellation Optimization

To compute $\binom{n}{r}$ without computing intermediate factorials that exceed memory limits, software systems employ incremental multiplicative reduction:

$$\binom{n}{r} = \prod_{i=1}^{r} \frac{n - r + i}{i}$$

Because each partial product represents $\binom{n - r + i}{i}$, the intermediate result is guaranteed to be an exact integer at every step, preventing floating-point precision loss and deferring overflow.


Production Implementations

Python: Arbitrary-Precision Multiplicative Implementation

import math

def calculate_npr(n: int, r: int) -> int:
    """
    Computes P(n, r) = n! / (n - r)! using continuous multiplication.
    Guarantees O(r) time complexity without calculating full n!.
    """
    if n < 0 or r < 0:
        raise ValueError("Parameters n and r must be non-negative integers.")
    if r > n:
        return 0
    if r == 0:
        return 1
    
    result = 1
    for i in range(n - r + 1, n + 1):
        result *= i
    return result

def calculate_ncr(n: int, r: int) -> int:
    """
    Computes C(n, r) using symmetry optimization and incremental division.
    Maintains exact integers at each step to prevent precision degradation.
    """
    if n < 0 or r < 0:
        raise ValueError("Parameters n and r must be non-negative integers.")
    if r > n:
        return 0
    if r == 0 or r == n:
        return 1
        
    # Exploit symmetry: C(n, r) == C(n, n - r)
    k = min(r, n - r)
    
    numerator = 1
    denominator = 1
    for i in range(1, k + 1):
        numerator *= (n - k + i)
        denominator *= i
        
        # Simplify intermediate fractions to prevent massive BigInt scaling
        common = math.gcd(numerator, denominator)
        if common > 1:
            numerator //= common
            denominator //= common
            
    return numerator // denominator

def calculate_stars_and_bars(categories: int, items: int) -> int:
    """
    Computes combinations with repetition: C(n + r - 1, r)
    """
    if categories <= 0 or items < 0:
        raise ValueError("Categories must be >= 1, items >= 0")
    return calculate_ncr(categories + items - 1, items)

# Demonstration
if __name__ == "__main__":
    n_val, r_val = 52, 5
    print(f"P({n_val}, {r_val}) = {calculate_npr(n_val, r_val):,}")
    print(f"C({n_val}, {r_val}) = {calculate_ncr(n_val, r_val):,}")
    print(f"Combinations with repetition (4 categories, 10 items) = {calculate_stars_and_bars(4, 10):,}")

TypeScript: BigInt Precision Implementation

export interface CombinatoricsResult {
  n: bigint;
  r: bigint;
  permutations: bigint;
  combinations: bigint;
  combinationsWithRepetition: bigint;
}

export function computeCombinatorics(nInput: number, rInput: number): CombinatoricsResult {
  if (!Number.isInteger(nInput) || !Number.isInteger(rInput)) {
    throw new TypeError("Inputs n and r must be integers.");
  }
  if (nInput < 0 || rInput < 0) {
    throw new RangeError("Inputs n and r cannot be negative.");
  }

  const n = BigInt(nInput);
  const r = BigInt(rInput);

  const permutations = computePermutation(n, r);
  const combinations = computeCombination(n, r);
  const combinationsWithRepetition = n > 0n ? computeCombination(n + r - 1n, r) : 0n;

  return { n, r, permutations, combinations, combinationsWithRepetition };
}

function computePermutation(n: bigint, r: bigint): bigint {
  if (r > n) return 0n;
  if (r === 0n) return 1n;

  let product = 1n;
  for (let i = n - r + 1n; i <= n; i++) {
    product *= i;
  }
  return product;
}

function computeCombination(n: bigint, r: bigint): bigint {
  if (r > n) return 0n;
  if (r === 0n || r === n) return 1n;

  // Symmetry optimization
  const effectiveR = r > n - r ? n - r : r;

  let numerator = 1n;
  let denominator = 1n;

  for (let i = 1n; i <= effectiveR; i++) {
    numerator *= (n - effectiveR + i);
    denominator *= i;
  }

  return numerator / denominator;
}

Systematic Model Comparison

Mathematical ConstructOrdered?Repetition Allowed?Primary ComplexityCanonical Application
Simple Permutation $P(n, r)$YesNo$O(r)$Award podiums, access code sequences, server job dispatching
Permutation with RepetitionYesYes$O(\log r)$ via exponentiationPassword keyspace enumeration, PIN cracking, DNA sequencing
Simple Combination $C(n, r)$NoNo$O(\min(r, n-r))$Lottery odds, card games, sub-committee selection
Combination with RepetitionNoYes$O(r)$Allocating identical CPU cores across disparate thread pools
Multiset PermutationYesConstrained$O(n)$Anagram solving, molecular isomer configuration analysis
Circular PermutationCyclicallyNo$O(n)$Network ring topologies, biochemical macro-ring cyclization

Critical Traps and Edge Cases

1. The $r > n$ Boundary Condition

In selections without replacement, attempting to choose more elements than exist in the set ($r > n$) yields zero valid configurations: $$\forall r > n: \quad P(n, r) = 0, \quad C(n, r) = 0$$ Naive factorial routines that compute $(n - r)!$ without checking $r > n$ attempt to evaluate the factorial of a negative integer, triggering an infinite recursion or mathematical domain fault.

2. Zero-Element Selection ($r = 0$)

Choosing 0 elements from any set size $n \ge 0$ yields exactly 1 configuration: the empty set $\emptyset$. $$\binom{n}{0} = \frac{n!}{0! , n!} = \frac{n!}{1 \times n!} = 1$$ This holds true even for $n = 0$: $\binom{0}{0} = 1$.

3. Floating-Point Roundoff in Scientific Computing

In languages lacking native arbitrary-precision integers (such as standard JavaScript numbers), evaluating expressions like factorial(25) / (factorial(5) * factorial(20)) using IEEE-754 double floats produces rounding artifacts. Always implement BigInt or iterative multiplicative simplification to maintain integer exactness.

4. Keyspace Entropy in Information Security

Permutations with repetition define cryptographic password search spaces: $$S = |\Sigma|^L$$ Where $|\Sigma|$ is the character set cardinality (e.g., 95 printable ASCII characters) and $L$ is string length. Password entropy $H$ in bits is given by: $$H = \log_2(S) = L \log_2(|\Sigma|)$$ Combinatorics directly dictates brute-force resistance thresholds for modern hashing algorithms.

Frequently Asked Questions

What is the core difference between permutation and combination?
In permutations, the sequence order matters (e.g., PIN codes or race podiums). In combinations, order does not matter (e.g., lottery numbers or team rosters).

Explore Related Utilities