complex integral $\int_0^{2\pi} (\cos x)^n \;dx$ I tried to solve following integral $$\int_0^{2\pi} (\cos x)^n \;dx$$
by saying $z = e^{ix}$ we get $dx=\frac{-i \;dz}{z}$ and $\cos x = \frac{1}{2}\left( z + \frac{1}{z}\right)$
$$\int_0^{2\pi} (\cos x)^n \;dx = \frac{-i}{2^n}\oint_{|z|=1} \frac{1}{z}\left( z + \frac{1}{z}\right)^n \; dz = 2\pi i \left( \frac{-i}{2^n} \right) \cdot Res(f(z) = \frac{z^2 + 1} {z^{n+1}}; z_0 = 0)$$
$$= \frac{\pi}{2^{n-1} n!} \left[ z^2 + 1\right]^{(n)}(0)$$
if $n=0$ we get $\frac{\pi}{2^{-1}} = 2\pi$, if $n=1$ we get $0$, if $n=2$ we get $\frac{\pi}{2!} = \frac{\pi}{2}$ and for $n = 3$ and $n > 3$ we get $0$.
But if I use integral solver for $n=4$ the result is $\frac{3\pi}{4}$ and for $n=2$ we get $\pi$. Why residue theorem doesn't work here? Or have I done some stupid mistake somewhere and I can't spot it?

You've just made a simple algebra mistake: notice that
$$\left(z + \frac1z\right)^n = \left(\frac{z^2 + 1}{z}\right)^n = \frac{(z^2 + 1)^n}{z^n}$$
so
$$\frac{-i}{2^n} \oint_{|z| = 1} \frac{1}{z}\left(z + \frac1z\right)^n dz = \frac{\pi}{2^{n-1}} \text{Res}_{z = 0}\left[\frac{(z^2 + 1)^n}{z^{n+1}}\right]$$
whereas your solution dropped the power of $n$ in the numerator.
Now, in order to efficiently find the necessary residue I would suggest considering a Laurent series: we can expand the power in the numerator using the binomial theorem:
$$(z^2 + 1)^n = \sum_{k = 0}^n \binom{n}{k} z^{2k}$$
so dividing by the denominator gives us our Laurent series:
$$\frac{(z^2 + 1)^n}{z^{n+1}} = \sum_{k = 0}^n \binom{n}{k} z^{2k-n-1}$$
and we just need to find the coefficient of $z^{-1}.$ This would require $2k = n,$ so for even $n$ we get a residue of $\binom{n}{n/2}$ and for odd $n$ we get no residue because there is no $z^{-1}$ term.
So, we get that the value of the desired integral is
$$\int_0^{2\pi} \cos^n(x) dx = \begin{cases}\frac{\pi\binom{n}{n/2}}{2^{n-1}} & n = 2k \\ 0 & n = 2k+1\end{cases}$$
for integers $n$ and $k.$
