Consider some function $f : \{1,2,\ldots,n\} \rightarrow \{1,2,\ldots,n\}$. I want to calculate $f^x$. It can be easily done in time $O(nx)$ where $n$ is the number of elements in the set.
I've found some formula $f^{2k+1} = f^{2k} f $ and my source says we can use this to do fast binary exponentiation. In fact I know how to calculate $a^x$ where $a$ is some integer using fast binary exponentiation, but I have no idea how to do it for functions/permutations.
Thanks for any hints.

A nice way to think about it is to notice that a function from any finite set to itself can be represented as a tuple, with the $i$th element giving the image of $i$ under the function: for example, $(2,3,4,1)$ is a representation of a function from the set $\{1,2,3,4\}$ to itself.
I'll write all my code using MATLAB syntax, as I think it's particularly easy to read, and arrays index from 1, which is sometimes pleasant for mathematicians.
Function composition is composition of tuples, and it can be computed in linear time:
I've inserted a line to display a message every time the function composition routine is called. The squaring operator is then easily defined:
And finally our exponentiation routine is:
We can now define a function and exponentiate it:
And there you have it - the composition function is called approximately $\log_2(x)$ times when we compose the function with itself $x$ times. It takes $O(n)$ time to do the function composition and $O(\log x)$ calls to the composition routine, for a total time complexity of $O(n\log x)$.