Let . If is divisible by , then . Otherwise, Fermat's little theorem allows us to reduce the exponent modulo .
Group indices as , where . The number of indices in group is
The integer may exceed the signed -bit range, so compute only
If , every term in that group contributes zero. Otherwise, define
Then the term at index satisfies
In particular, the first term is , not necessarily : congruence of the base modulo does not imply congruence of its exponent modulo .
The sum within a group is if , and otherwise
Use a modular inverse for division. Since , also , so exponent reduction modulo is valid. Precompute inverses from to in linear time.
Add the contributions of every group. There are at most groups, and each requires time for modular exponentiation. The overall time complexity is and the space complexity is . By reducing operands before multiplication, all intermediate values fit in signed -bit integers.
Solution written by GPT6