快速幂
Posted walterj726
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速幂相关的知识,希望对你有一定的参考价值。
快速幂的用法及推导
之前算一个(a^k)时间复杂度是(O(K)).搞一个循环不断的相乘
现在是(O(logk))
在30次之内算出来
核心思想:反复平方法
等号两边同时模一个数,那个大小是不变的
代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL qmi(int a, int n, int mod)
{
LL res = 1 % p; // 当 p = 1, b = 0的时候是有区别的
while(n)
{
if(n & 1) res = res * a % mod;
a = a * (LL) a % mod;
n >>= 1;
}
return res;
}
int main()
{
int n;
cin >> n;
while(n--)
{
int a, b, p;
cin >> a >> b >> p;
cout << quick_mod(a, b, p) << endl;
}
return 0;
}
快速幂求逆元
除法取余数是很麻烦的一件事情
a/b = ax (mod m)
x是b的mod m的逆元
逆元是一个整数只是一个标记
相除不一定是整数,相乘是整数
bx mod m == 1
费马定理
以上是关于快速幂的主要内容,如果未能解决你的问题,请参考以下文章