372. Super Pow

首先,有这么一个公式:
a^b mod c = (a mod c)^b mod c
(ab) mod c = (a mod c)(b mod c) mod c
之后的事情就简单了,可以使用简单的按位迭代的方式解决这道题:

class Solution {
    const int base = 1337;
    int powmod(int a, int k) //a^k mod 1337 where 0 <= k <= 10
    {
        a %= base;
        int result = 1;
        for (int i = 0; i < k; ++i)
            result = (result * a) % base;
        return result;
    }
public:
    int superPow(int a, vector& b) {
        if (b.empty()) return 1;
        int last_digit = b.back();
        b.pop_back();
        return powmod(superPow(a, b), 10) * powmod(a, last_digit) % base;
    }
};

你可能感兴趣的:(372. Super Pow)