Solving $\text{key}=(\sum_{K=0}^n\frac{1}{a^K})\bmod m$ with High limits
Solve a linear homogeneous recurrence to obtain the identity $$\sum_{K=0}^n\frac1{a^K}=\begin{cases}\frac{1-1/a^{n+1}}{1-1/a}&amp;\text{if }a\neq1\pmod m\\n+1&amp;\text{if }a=1\pmod m\end{cases}$$ and use efficient algorithms for multiplicative inversion and exponentiation mod $m$.