As the link on Wikipedia says, and I have read it in many other books as well, if we use squaring in exponentiation for modular exponentiation the complexity reduces and cuts down to $O(\log n)$, where $n$ is the exponent.
- What I do not get here is that when we are using modular exponentiation modulo $p$, why aren't we taking into account that modulo when calculating the complexity? For larger numbers, if we keep on taking squares until we reach $n$ the resulting number will be extremely huge, so we have to compute modulo $p$ at almost every step. Now shouldn't that increase the complexity? Or im wrong in assuming that we need to take mod at every step?
- Can we do this squaring in the exponentiation process for any base like $6$ or $10$ or we have to stick with $2$?
You do need to work modulo p at each step. Let's say you are doing $x^m$ with $m$ being $b+1$ bits long. You write this as a product of some of $x^{2^b} \cdots x^{2^1}, x^{2^0}$ where the positions of the 1 bits in m tell you which ones to use. Going from $x^{2^k}$ to $x^{2^{k+1}}$ is squaring modulo p. So to get all of them you need you have to do $b$ squaring operations. Then you have to multiply some of these together. Say there are $l$ 1 bits in $m$. That means an additional $l$ multiplications modulo $p$. A total of $b+l$ but that is approximately proportional to $\log m$ not $m$.