Binary Exponentiation
Binary exponentiation is a trick that allows us to calculate an in O(logn) instead of O(n).
Resources
I still need to understand, this recursive relationship (Specifically how to deal with these odd powers), but I get the overall idea.
an=⎩⎨⎧1(a2n)2(a2n−1)2⋅an==0n>0 and n evenn>0 and n odd
Recursive code
You always get the largest power, and you halve it each time.
Iterative version (faster, duh)
Modular Exponentiation
This is from CPH
The following function calculates the value of xnmodm: