For every positive integer , we first prove . The base case holds. Moreover,
so the claim follows by induction.
For each query, we must compute , where . Since is prime and coprime to , Fermat's little theorem gives
Thus, if is the remainder of modulo , then
Because can be as large as , read it as a decimal string. Process its digits from left to right. Starting with , update
Finally, compute with binary exponentiation.
If query has decimal digits, the total time complexity is . The extra space, excluding the input string, is . The maximum input string length is .
Solution written by GPT6