Subfactorial calculator
Count the derangements of n items, the arrangements where nothing stays in its original place: the subfactorial of 4 is 9, and you also get the chance that a random shuffle is one of them. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Number of items n
- 0
- Derangement count
- 1
- Derangement probability
- 1
Computes the subfactorial ! n, the number of derangements of n items — permutations in which nothing stays in its original position. From an integer n it returns the derangement count and the probability that a random permutation is a derangement.
What the subfactorial counts and the series used
The subfactorial ! n counts derangements: the permutations of n distinct items in which no item is left in its original position. This capability evaluates it from the alternating series !
n = n! · Σ (−1)^k / k! for k running from 0 to n, which is the classic inclusion–exclusion result. The implementation accumulates that sum term by term while building k!
incrementally, then multiplies by n! and rounds to the nearest integer to absorb floating-point noise, so the returned value is an exact integer count. The first values are !
0 = 1, ! 1 = 0, ! 2 = 1, ! 3 = 2, ! 4 = 9 and ! 5 = 44.
The single empty permutation of zero items is vacuously a derangement, which is why ! 0 = 1, while a single item can never move so ! 1 = 0.
The derangement probability and its link to 1/e
Alongside the count the tool returns probability, the chance that a permutation of n items drawn uniformly at random is a derangement, computed as value / n! Because the series above is exactly the truncated Taylor expansion of e^(−1), this probability converges very quickly to 1/e ≈ 0.367879 as n grows. It is already close at small n: !
4 = 9 out of 4! The probability is rounded half-up to six decimal places by default. This is the mathematical heart of the classic hat-check or secret-Santa problem, where the answer barely changes once the group is larger than a handful of people.
Input range, rounding and validation
The only required input is n, which must be an integer from 0 to 20. The upper bound of 20 is deliberate: 20! is about 2.43 × 10^18, near the edge of what a double-precision float represents exactly, so capping n keeps the integer derangement count exact rather than silently losing precision.
The optional decimals parameter controls half-up rounding of the probability.
What you can do with it
Secret Santa and gift exchanges
Compute the probability that a random draw leaves nobody assigned to themselves, or count the valid derangements, before running a gift or partner assignment.
Combinatorics coursework
Produce exact !n values and the inclusion–exclusion probability to build answer keys or check derived formulas against the closed-form series.
Randomised test design
Quantify how likely a shuffled permutation leaves an item in place, useful when generating scrambles that must move every element.
FAQ
What is a subfactorial?
The subfactorial ! n is the number of derangements of n items — permutations where no item stays in its original position — given by n! ·Σ(−1)^k/k!.
Why is !0 equal to 1 and !1 equal to 0?
The empty permutation of zero items is vacuously a derangement, so ! 0 = 1; a single item cannot avoid its own place, so ! 1 = 0.
What is the derangement probability?
It is value / n!, the chance a random permutation is a derangement. It converges rapidly to 1/e ≈ 0.367879 as n increases.
What values of n are allowed?
n must be an integer from 0 to 20; the cap keeps the count exact in double precision.
In how many ways can 5 people draw names so nobody gets their own?
In 44 ways, the subfactorial of 5. For four people the count is 9 out of 24 possible draws, and the calculator also turns that share into a probability, 0.375, so you can judge a Secret Santa draw before running it.
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/math/subfactorial \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"n":4}'const res = await fetch("https://api.kit.forhosting.com/math/subfactorial", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"n": 4
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/math/subfactorial",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"n": 4
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/math/subfactorial", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"n":4}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"n":4}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/math/subfactorial", 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": 4
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "math.subfactorial",
"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.
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
The derangement probability and its link to 1/e
(and defined as 1 for n = 0). = 24 gives 0.375, and by n = 6 or 7 the value is indistinguishable from 1/e at everyday precision.
Input range, rounding and validation
A non-integer, a negative value, or n above 20 raises a typed invalid_input error with the message "n inválido", letting a form or client react on the error code without parsing text.
Technical questions
Is it free and how do I automate it?
The tier A widget runs free in your browser; the deterministic API returns the same value and probability JSON from $0.002 per call.