First, note that c * A^n
is never an exact multiple of B = 456
since the former is always odd and the latter is always even. You can generalize this by considering the prime factorizations of the numbers involved and see that no repetition of the factors of c
and A
will ever give you something that contains all the factors of B
. This means c
will never turn into 0
as a result of the iterated multiplication.
There are only 456 possible values for c * a
mod B = 456
; therefore, if you iterate the loop 456 times, you will see at least value of c
repeated. Suppose the first value of c
that repeats is c'
, when i= i'
. Say it first saw c'
when i=i''
. By continuing to iterate the multiplication, we would expect to see c'
again:
- we saw it at
i''
- we saw it at
i'
- we should see it at
i' + (i' - i'')
- we should see it at
i' + k(i' - i'')
as well
Once you detect a repeat you know that pattern is going to repeat forever. Therefore, you can compute how many patterns are needed to get to N, and the offset in the repeating pattern that you'd be at for i = N - 1
, and then you'd know the answer without actually performing the multiplications.
A simpler example:
A = 2
B = 3
C = 5
c[0] = 5
c[1] = 5 * 2 % 3 = 1
c[2] = 1 * 2 % 3 = 2
c[3] = 2 * 2 % 3 = 1 <= duplicate
i' = 3
i'' = 1
repeating pattern: 1, 2, 1
c[1+3k] = 1
c[2+3k] = 2
c[3+3k] = 1
10,000 = 1 + 3k for k = 3,333
c[10,000] = 1
c[10,001] = 2
c[10,002] = 1