A derangement is a permutation of size $n$ such that for all $1 \leq i \leq n$ we have $p(i) \neq i$.

How many derangements of size $n$ are there?
We will instead count the permutations of size $n$ that have at least one $i$ such that $p(i)=i$. For this, we will use the principle of inclusion and exclusion.

Let $A_{i}$ be the set of permutations such that $p(i)=i$. We then have: $\operatorname{Card}\left(A_{i}\right)=(n-1)!$ and for an intersection of $k$ distinct sets $A_{i}$ we have $\operatorname{Card}\left(A_{i_{1}} \cap A_{i_{2}} \cap \cdots \cap A_{i_{k}}\right)=(n-k)!$. Therefore, using the formula of the principle of inclusion and exclusion, we have:

$$
\operatorname{Card}\left(A_{1} \cup A_{2} \cup \cdots \cup A_{n}\right)=\binom{n}{1}(n-1)!-\binom{n}{2}(n-2)!+\cdots+(-1)^{n-1}
$$

Since there are $n!$ permutations, the number of derangements is:

$$
n!-\left(n!-\frac{n!}{2!}+\frac{n!}{3!}-\cdots+\frac{(-1)^{n-1} n!}{n!}=n!\left(\frac{1}{2!}-\frac{1}{3!}+\cdots+\frac{(-1)^{n}}{n!}\right)\right.
$$