Given integers $p \ge 2$ and $n \ge 1$, I am analyzing the sequence of powers $S = (p^0, p^1, p^2, \dots) \pmod n$.
I know this sequence is always eventually periodic. For example:
If $p=2, n=7$, the sequence becomes (1, 2, 4, 1, 2, 4, ...) which is a pure cycle of length 3.
If $p=2, n=12$, the sequence is (1, 2, 4, 8, 4, 8, ...) which has a pre-period (tail) of (1, 2) and a cycle (4, 8) of length 2.
My question is: Is there a formal method to determine the length of the pre-period and the length of the cycle for any given $p$ and $n$, without having to compute the sequence term by term until a repetition is found?