自用笔记-快速幂
快速幂代码:
#include<cstdio> #include<cstdlib> #include<cmath> #include<ctime> #include<cstring> #include<string> #include<algorithm> #include<iostream> using namespace std; typedef long long LL; int a, b, pt = 1e3; //根据实际需求设置pt int res; LL Pow(int x, int y){ LL ans = 1; while(y != 0){ if(y & 1){ ans *= x % pt; //取余防止数据过大 } y >>= 1; x *= x % pt; } return ans; } int main() { scanf("%d%d", &a, &b); res = Pow(a, b); printf("%d\n", res); return 0; }
关于取余的一些补充:
有这样一个公式: ab % c = (a % c)b % c
------------------------------------------------------------------------------------------------------------------------------
引理: (ab)b % c = [(a % c) * (b % c)] % c
证明 a % c = d => a = tc + d
b % c = e => b = kc + e
(ab) % c = (tc + d)(kc + e) % c
= (tkc2 + (te + dk) + de) % c
= de % c = [(a % c) * (b % c)] % c
即 积的取余等于取余的积的取余
由此可推广到 ab % c = (a % c)b % c 也成立