Forget about the modular part for a while, and ask yourself, “How can I efficiently calculate x^n for n a positive integer?” You can calculate x^2 with one multiplication: x * x. You can calculate x^3 with two multiplications: x^3 = x * x^2. You can calculate x^4 with two multiplications: x^4 = x^2^2 = x^2 * x^2. You can calculate x^n in general with this recursion:
For even n = 2*m, x^n = (x^2)^m.
For odd n = 2*m + 1, x^n = x * (x^m)^2.
So, we get x^10 as:
x^10 = (x^2)^5
= x^2 * (x^4)*2
Compute x^2, x^4, x^8, x^10, for 4 multiplications.
Note that this is a good general method, but it is not guaranteed to be the most efficient. Try x^15, for example. This method gives you x * (x^2)^7 = x * x^2 * (x^2)^6 = x * x^2 ^ (x^4)^3 = x ^ x^2 * x^4 * (x^4)^2. You compute x^2, x^4, x^8, and then x * x^2 * x^4 * x^8, for 6 multiplications. Faster is
y = x^3 = x * x^2, 2 multiplications.
x^15 = y^5 = y * (y^2)^2, 3 more multiplications,
This is a total of 5 multiplications.
In fact, for an exponent n, define an addition chain as a sequence of numbers starting at 1 and ending at n, where each number in the list is the sum of 2 previous numbers in the sequence (and you can repeat).
The algorithm for 15 gives
1, 2, 3, 6, 7, 14, 15.
The shorter one is
1, 2, 3, 6, 12, 15.
It turns out to be computationally hard to find the shortest addition chain ending at a target number.