给自己做个记录
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <string>
#include <stdio.h>
#include <sstream>
#include <vector>
#include <cstddef>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <list>
using namespace std;
//快速幂,a的b次方
int Pow(int a,int b){
int ans = 1;
int base = a;
//将b视为二进制,当b不为0时
//(举个栗子:a为2,b为11,即1011,2^11 = 2^1 * 2^2 * 2^8
while(b){
//b与1作与,即取b的最后一位,如果为1则ans乘base
//(取1,1,0,1,分别代表2^1,2^2,不乘,2^8
if(b & 1) ans *= base;
//base一直作叠乘,保证随时可以为ans服务(取1,1,0,1时base分别等于2^1,2^2,2^4,2^8
base *= base;
//b右移一位
b >>= 1;
}
return ans;
}
//快速幂取余
//定理:(a*b) mod c = (a mod c) * (b mod c) mod c
//推论:a^b mod c = (a mod c)^b mod c
int pow_mod(int a,int b,int c){
int ans = 1;
//先将base定为a mod c
int base = a % c;
while(b){//继续拿上个栗子,a = 2,b = 11,c = 7,即2^11 mod 7
//一直模c是为了缩小底数的规模
if(b & 1) ans = (ans * base)%c;//第二次,(a mod c) * (a mod c)^2 mod c = (a mod c)^3 mod c
base = (base*base)%c;//第一次,(a mod c)*(a mod c) mod c = (a mod c)^2 mod c
b >>= 1;
}
return ans;
}
int main()
{
//朴素算法
cout << pow(2,11) << endl;
//快速幂算法
cout << Pow(2,11) << endl;
//朴素算法
cout << (int)pow(2,11)%7 << endl;
//快速幂算法
cout << pow_mod(2,11,7) << endl;
return 0;
}