← O(n!) — factorial complexity
docs: English JsonRpcBundle docs, REST and MCP Bundle sections, package cards
en/articles/from-tg/series/algorithm-complexity/o-n-factorial.md
new file +39
−0
1
+
# O(n!) — factorial complexity
2
+
3
+
This is the peak of computational nightmares. Factorial complexity means the number of operations grows as the product of all integers up to n. For n = 10, that's already 3,628,800 variants. And yes, all of them have to be processed.
4
+
5
+
```text
6
+
10! = 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 = 3 628 800
7
+
```
8
+
9
+
## Example: generating all possible permutations of elements
10
+
11
+
```php
12
+
function permutations(array $items): array {
13
+
if (count($items) <= 1) return [$items];
14
+
15
+
$result = [];
16
+
foreach ($items as $key => $item) {
17
+
$remaining = $items;
18
+
unset($remaining[$key]);
19
+
foreach (permutations(array_values($remaining)) as $perm) {
20
+
$result[] = array_merge([$item], $perm);
21
+
}
22
+
}
23
+
return $result;
24
+
}
25
+
```
26
+
27
+
This code generates all possible permutations of the array's elements. And if there are 8 of them, that's already 40,320 variants. It may look innocent — until production goes down on Black Friday.
28
+
29
+
:::tip
30
+
Factorial complexity is always a last resort. If a task involves trying every option, first look for an approximation, a greedy algorithm or a heuristic.
31
+
:::
32
+
33
+
That's the end of the series.
34
+
35
+
← [Previous: O(2ⁿ) — exponential complexity](/articles/from-tg/series/algorithm-complexity/o-2n) · [Whole series](/articles/from-tg/series/algorithm-complexity)
36
+
37
+
---
38
+
39
+
*First published in Ukrainian in the Telegram channel [“Created to die”](https://t.me/php_while_true/51) on June 27, 2025.*