TITLE: Simplifying large exponents in modular arithmetic like $1007$ in $4^{1007} \pmod{5}$
QUESTION [11 upvotes]: How would I rigorously prove that $4^{1007} \pmod{5} = 4$ and $4^{1008} \pmod{5} = 1$?
I was simplifying a larger modular arithmetic problem ($2013^{2014} \pmod{5}$) and got it down to $4^{1007} \pmod{5}$ and am wondering if there's a general approach to dealing with large exponents like $1007$.
In general, what approaches are there to simplify large exponents like $1007$ when doing modular arithmetic?

REPLY [2 votes]: Another method for this is repeated squaring.
Take $n^d \mod b$ then
find all $a^{2^k} \mod b$ for all $2^k <= d$  where $d$ is $n^d$ 
$$\begin{align}
4^2 &= 16 = 1 \\
4^4 &= (4^2)^2 = 1^2 \\
4^8 &= (4^4)^2 = 1^2 \\
&... \\
4^{512} &= 1 \\
\end{align}$$
for $4^{1007}$ we have:
$$\begin{align}
4^{1007} 
  &= 4^{512} * 4^{256} * 4^{128} * 4^{64} * 4^{32} * 4^8 * 4^4 * 4^2 * 4  \\
  &= 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 4 \mod 5 \\
  &= 4 \mod 5  
\end{align}$$
and for $4^{1008}$ we have:
$$\begin{align}
4^{1008}
  &= 4^{512} * 4^{256} * 4^{128} * 4^{64} * 4^{32} * 4^{16} \\
  &= 1 * 1 * 1 * 1 * 1 * 1 \\
  &= 1 \mod 5 \\
\end{align}$$
Further details:
http://www.tricki.org/article/To_work_out_powers_mod_n_use_repeated_squaring