We have a similar idea. I speed it up a bit by the fact that 1337^3 will cause overflow but not 1337^2. Thus, it is safe to use a * a % 1337 since a < 1337 implies that a * a would not cause overflow as well.

class Solution { private: int base = 1337; public: int superPow(int a, vector<int>& b) { a %= base; if (b.size() == 1) { int ret = 1; while (b[0] >= 2) { ret = ret * (a * a % base) % base; b[0] -= 2; } return (int) pow(a, b[0]) * ret % base; } vector<int> bLast = {b.back()}; b.erase(b.end()-1); return superPow(power10mod1337(a), b) * superPow(a, bLast) % base; } int power10mod1337(int a) { int a2 = a * a % base; int a4 = a2 * a2 % base; return (a4 * a4 % base) * a2 % base; } };Any suggestion would be appreciated.