Derangement calculator
Count the shuffles in which nothing stays in its original spot: 5 people drawing names for secret Santa have 44 draws where nobody gets themselves, which is !5. Results stay exact for large n. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- N
- 5
- Derangements
- 44
- Notation
- !5
A derangement is a permutation of n items in which no element appears in its original position — the classic hat-check problem, secret Santa without self-gifts, and shuffled decks that avoid fixed cards all ask the same count. That count is the subfactorial ! n, also written d(n) or D_n. This calculator evaluates ! n with the deterministic recurrence ! 0 equals one, ! 1 equals zero, and for every larger n the value is n minus one times the sum of the two previous subfactorials, implemented with BigInt so classroom and interview-scale answers stay exact. Negative n is rejected with a clear validation error because the sequence is only defined for non-negative integers.
What derangements count and when the subfactorial matters
A derangement of a finite set is a bijection with no fixed points: every item moves. The number of such permutations of an n-element set is the subfactorial ! n. The story that made the concept famous is the hat-check problem: n guests check n hats and each receives a random hat; how many ways can every guest get a wrong hat?
Secret Santa draws, seating plans that ban everyone from their usual chair, and coding problems that ask for permutations without fixed indices are the same combinatorial object under different names. The sequence begins ! 0 equals one by the empty-product convention, !
1 equals zero because a single item cannot move, ! 2 equals one, ! 3 equals two, !
4 equals nine, and ! 5 equals forty-four. For large n the ratio !
n over n! approaches one over e, which is why probability courses quote that a random permutation is a derangement with probability near thirty-seven percent. Full factorials count all permutations including those with fixed points; permutations P(n,r) count ordered samples of size r; combinations ignore order entirely. If your question is specifically how many ways nothing stays put, you need the subfactorial, not those other tools.
This capacity returns only that ordered fixed-point-free count so searchers looking for a derangement or subfactorial calculator land on the formula they actually need.
How this calculator evaluates !n and validates input
The engine checks that n is present as a finite non-negative integer at most the published upper bound of ten thousand. For accepted n the implementation walks the recurrence from the base cases: start with ! 0 equals one and !
1 equals zero, then for each k from two through n set ! k equal to k minus one times the sum of ! k minus one and !
k minus two, using BigInt arithmetic throughout. That recurrence is algebraically equivalent to the inclusion-exclusion form ! n equals n factorial times the alternating sum of reciprocal factorials, but the recurrence never needs floating-point division and never materializes a full factorial.
The response also echoes n, a notation string such as exclamation five, and a short formula note describing the recurrence or the base case. Edge cases are explicit: ! 0 is one and !
Practical use, limits, pricing, and delivery
Use the browser tool when you want an immediate exact ! n while studying discrete math, checking a contest answer, or explaining the hat-check problem without installing a computer-algebra system. Accepted indexes run from zero through ten thousand so classroom demos and combinatorial filters remain feasible without unbounded memory growth on pathological products.
Results are fully deterministic: the same n always yields the same derangements value, notation, and formula fields. There is no language model, no external arithmetic service, and no randomness, so the capability is safe to pin in continuous-integration checks and reproducible lesson materials.
What you can do with it
Homework and contest verification
Students and graders confirm !n for hat-check and secret-Santa problems without a local computer-algebra system, including base cases !0=1 and !1=0.
Sample-space sizing for fixed-point-free models
Pipelines that model random derangements can call a deterministic subfactorial oracle instead of reimplementing BigInt recurrence in every language.
Teaching derangements versus full permutations
Lesson pages that contrast n! with !n can show exact counts beside the recurrence so learners connect subfactorial notation to permutations with no fixed points.
FAQ
What is the subfactorial formula for !n?
Base cases are ! 0=1 and ! 1=0. For n≥2, ! n=(n−1)(!( n−1)+!( n−2)). Equivalently ! n=n×!( n−1)+(−1)^n. The count is the number of permutations with no fixed points.
What happens if n is negative?
Derangements are only defined for non-negative integers; those calls are not charged.
Is the derangement calculator free?
The browser tool runs free on your device.
How do derangements differ from ordinary permutations?
The factorial n! counts all permutations of n items. The subfactorial ! n counts only those with no fixed points. For large n, ! n/n! approaches 1/e ≈ 0.3679.
What is the chance that a random shuffle leaves nothing in place?
For larger n it approaches one over e, close to thirty-seven percent. That is the subfactorial !n divided by n!, the count of all possible orderings of the same items.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/combo/derangement \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"n":5}'const res = await fetch("https://api.kit.forhosting.com/combo/derangement", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"n": 5
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/combo/derangement",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"n": 5
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/combo/derangement", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"n":5}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"n":5}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/combo/derangement", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"n": 5
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "combo.derangement",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Limits
max_n | 10000 |
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
How this calculator evaluates !n and validates input
Send a JSON body with the required integer field n. If n is negative the request fails immediately with invalid_input naming that domain rule, and the call is not charged. Missing fields, non-integers, non-finite values, and values above the limit also fail with invalid_input. The product is returned as a JSON number when it fits inside the safe integer range, otherwise as a decimal string so clients never lose high-order digits.
Practical use, limits, pricing, and delivery
Each successful request is one billable item at $0.002; failed validation does not consume balance. Wire the endpoint into combinatorics demos, coding-interview sandboxes, probability tutorials that need the size of the fixed-point-free sample space, or integer preprocessing steps where you already prefer exact subfactorial arithmetic over approximate e-based heuristics or opaque black-box calculators that cannot show the recurrence structure or the domain restriction when n is negative.
Technical questions
How do I compute the number of derangements of n with this API?
Send a JSON body with integer field n to combo.derangement. The response returns derangements, notation such as !5, and a short formula note for the recurrence.