快速幂板子
#include<iostream> using namespace std; int n, a, b, p; long long qmi(int a, int b, int p){ long long res = 1; while(b){ if(b & 1) res = (long long) res * a % p; b >>= 1; a = (long long) a * a % p; } return res; } int main(){ cin >> n; while(n --){ cin >> a >> b >> p; cout << qmi(a, b, p) << endl; } return 0; }
class Solution { public: vector<int> getGoodIndices(vector<vector<int>>& variables, int target) { vector<int> res; // 快速幂板子 auto qmi = [&](int a, int b, int p) -> long long{ long long ans = 1; while (b){ if (b & 1) ans = (long long) ans * a % p; b >>= 1; a = (long long) a * a % p; } return ans; }; for(int i = 0; i < variables.size(); i ++){ int a = variables[i][0], b = variables[i][1], c = variables[i][2], m = variables[i][3]; int t1 = qmi(a, b, 10); int t2 = qmi(t1, c, m); if(t2 == target) res.push_back(i); } return res; } };
注意n的范围可能会超出int限制,开成long long
class Solution { public: double myPow(double x, int n) { double res = 1; bool f = 0; long long b = n; if (n < 0) f = 1, b = -b; while (b){ if(b & 1) res = res * x; b >>= 1; x = x * x; } if (f) return 1 / res; return res; } };