倍增:64位整除法
题目:P10446 64位整数乘法 - 洛谷
思路与快速幂类似。原来是a 次方 b 对 p取模,现在是a 乘 b 对 p 取模。
把乘法的部分改成加法就好了。
#include <iostream>using namespace std;
typedef long long LL;LL a, b, p;LL qpow()
{LL ret = 0; //记得这里初始化是0while(b){if (b&1) ret = (ret+a)%p;a = (a+a)%p;b >>= 1;}return ret;
}int main()
{cin >> a >> b >> p;cout << qpow() << endl;return 0;
}
时间复杂度为O(logb)