// 本题 mod 很小,即使平方也不会超过 int 范围,所以不需要用 long long intpow(int x, int n, int mod){ // long long res int res = 1; while (n) { if (n & 1) { res = res * x % mod; } x = x * x % mod; n >>= 1; } return res; }
快速幂实现思路(workflow)如下图:
代码实现时,注意 n=−$2^{31}$ 的情况,取反后 n=$2^{31}$ 超出 int 最大值。可以转成 64 位 int 解决(即 long long)
classSolution { public: doublemyPow(double x, int N){ double ans = 1; longlong n = N; if (n < 0) { // x^-n = (1/x)^n n = -n; x = 1 / x; } while (n) { // 从低到高枚举 n 的每个比特位 if (n & 1) { // 这个比特位是 1 ans *= x; // 把 x 乘到 ans 中 } x *= x; // x 自身平方 n >>= 1; // 继续枚举下一个比特位 } return ans; } };
intqpow(int x, int n){ int res = 1; // due to dfs() x %= MOD; while (n) { if (n & 1) { res = res * x % MOD; } x = x * x % MOD; n >>= 1; } return res; }
intdfs(int a, vector<int>& b, int idx){ if (idx == -1) return1; returnqpow(a, b[idx]) * qpow(dfs(a, b, idx - 1), 10) % MOD; }