I need to do this for a programming contest, but I thought it would be a better fit here.
I need to perform the following computation multiple times:
$$ x = ((x \cdot a) + b) \% M $$
Basically I need to do:
for(int i=0;i<n;i++){
x = (x*a)%M;
x = (x+b)%M;
}
where $M = 1000000007$ and $n \approx 10000$. Is there a way to speed up this computation and get the value of $x$ directly?
If it is not necessary to honestly run the loop $n$ times, we can take advantage of the fact that the answer takes an explicit form: If $x_n$ denotes the output after the $n$-th loop, then
$$ x_n \equiv a^n x + (1 + a + \cdots + a^{n-1})b \mod{M} $$
Assuming that $a$ is an integer, the speed of computation can be boosted by considering an iteration. More precisely, if we define
$$ f(n, a) = \sum_{k=0}^{n-1} a^k = 1 + a + \cdots + a^{n-1}, $$
then for integers $a$ and $n \geq 1$, it satisfies
$$ f(n, a) \equiv \begin{cases} 1, & n = 1; \\ 1+a, & n = 2; \\ (1+a)f(n/2, a^2), & \text{$n$ is even}; \\ 1+(a+a^2)f((n-1)/2, a^2), & \text{$n$ is odd}; \end{cases} \mod{M}$$
So, instead of performing $n$ linear operations, it suffices to perform $\mathcal{O}(\log_2 n)$ iterations. For instance, the following is an implementation of this idea to Python code:
In my computer, the result of this code is
As we can see, this method is useful when $n$ is very large.