I'm a non-mathematician but I've been reading up on number theory as part of furthering my understanding of cryptography, and I've been focusing particularly on modular arithmetic in $\mathbb{Z}_p$ for $p > 2$, where $p$ is prime.
I'm mostly understanding it, but I came across the following example:
$$2^{-1}\textrm{ in }\mathbb{Z}_p\textrm{ is }\frac{p+1}{2}$$
This appears to work, and I can't find any counterexamples, but I'm struggling to understand whether it's a special case for $x=2$ or part of a more general rule, or where this identity was even derived from.
Further confusing me is that $x^{-1}=x^{p-2}$ in $\mathbb{Z}_p$ for $x \neq 0$, which would imply that $2^{p-2}\equiv\frac{p+1}{2}$ in $\mathbb{Z}_p$ for all prime $p > 2$, and I can't see how this arises.
How does this work?