The whole question is here:
Show that, if there exists $a\in\Bbb Z$ such that $a^{m-1}\equiv 1\pmod m$ and $a^k\not\equiv 1\pmod m$ for each $0<k<m-1$, then $m$ is prime.
I know the opposite way is fermat's theorem but don't how to prove in this way.