1.1 Fast power
[算法学习笔记(4):快速幂 - 知乎 (zhihu.com)]
-
a^b
//Recursion #include<iostream> using namespace std; long long pow(int a, int b) { if (b == 0) { return 1; } else if (b % 2 == 1) { return pow(a, b - 1) * a; } else { long long t = pow(a, b / 2); return t * t; } } int main() { int a, b; while (~scanf("%d %d",&a,&b)) { cout << pow(a, b) << endl; } return 0; }
//bit operation #include<iostream> using namespace std; long long pow(int a, int b) { long long ans = 1; while (b) { if (b & 1)//The last binary bit of b is 1. { ans *= a; } a *= a;//Power increases in multiples. b >>=1;//b's binary bit is shifted one bit to the right. } return ans; } int main() { int a, b; while (~scanf("%d %d", &a, &b)) { cout << pow(a, b) << endl; } return 0; }
-
a^b\mod p
//bit operation #include<iostream> using namespace std; long long pow(int a, int b,int p) { long long ans = 1; while (b) { if (b & 1)//The last binary bit of b is 1. { ans *= a%p; } a *= a%p;//Power increases in multiples. b >>=1;//b's binary bit is shifted one bit to the right. } return ans; } int main() { int a, b,p; while (~scanf("%d %d %d", &a, &b,&p)) { cout << pow(a, b,p) << endl; } return 0; }
-
a*b \mod p
#include<iostream> using namespace std; #define ll long long ll pow(ll a, ll b, ll p) { ll ans = 0; while (b) { if (b & 1) { ans = (ans+a) % p; } a =a*2 % p; b >>= 1; } return ans; } int main() { ll a, b, p; while (~scanf("%lld %lld %lld", &a, &b, &p)) { cout << pow(a, b, p) << endl; } return 0; }