Simplifying large exponents in modular arithmetic like $1007$ in $4^{1007} \pmod{5}$

To answer the general question, there are two handy ways of simplifying $$a^k \pmod n.$$

Method 1

We have the property of modulo arithmetic: If $a \equiv b \pmod n$ and $c \equiv d \pmod n$, then $ac \equiv bd \pmod n$. This has the corollary:

If $a \equiv b \pmod n$ then $a^k \equiv b^k \pmod n$ for all $k \geq 1$.

In this case, we see $4 \equiv -1 \pmod 5$. So $$4^{1007} \equiv (-1)^{1007} \pmod 5.$$ But we know $(-1)^{1007}=-1$ since $1007$ is odd. So $$4^{1007} \equiv -1 \pmod 5.$$ We can then multiply both sides by $-1$ to show $$4^{1008} \equiv 1 \pmod 5.$$

Method 2

Euler's Theorem, which implies that if $\gcd(a,n)=1$, then $a^{\varphi(n)}=1 \pmod n$, where $\varphi$ is the Euler phi-function. This has the consequence:

If $\gcd(a,n)=1$ then $$a^k \equiv a^{k \text{ mod } \varphi(n)} \pmod n$$ for all $k \geq 1$.

So, in the example, we compute $\varphi(5)=4$ (since $5$ is prime), then we know $$4^{1007} \equiv 4^{1007 \text{ mod } 4} \equiv 4^3 \equiv 4 \pmod 5.$$ We can then multiply by $4$ to show $$4^{1008} \equiv 1 \pmod 5.$$


First of all, some common sense can help a lot and even without Fermat's theorem:

$$4=-1\pmod 5\implies\begin{align*} 4^{1007}&=(-1)^{1007}=-1=4\pmod 5\;,\\{}\\ \;\;4^{1008}&=(-1)^{1008}=1\pmod 5\end{align*}$$


Use Fermat's Theorem which tells that if $p$ is a prime and $gcd(a,p)=1$, then $a^{p-1}\equiv 1(\mod~p)$.

For further elaboration on Fermat's Theorem see http://mathworld.wolfram.com/FermatsLittleTheorem.html or any standard text in Number Theory.