Quick power:
Description: Find the b power of a and then take the remainder m
Usually written: open an int ans=0,ans = ans * a% m, execute it b times in total:
for(int i=0;i<b;i++)
{
ans = ans * a % m;
}
cout << ans;
"Obviously time is not good enough."
Quick power idea: Based on the idea of dichotomy, if b is odd: a to the b power = a a to the b-1 power,
if b is an even number, a to the b power = a to the b/2 power * a To the power of b/2.
For example : the 10th power of 2 = the 5th of a * the 5th of a
2 the 5th = 2 the 4th of 2
...
Until the 0th of 2 is equal to 1, return;
ll binaryPow(ll a, ll b, ll m)
{
if (b == 0) return 1; //如果0次幂 ,返回1
if (b % 2 == 1) return a * binaryPow(a, b - 1, m) % m; //幂是偶数情况
else {
ll temp = binaryPow(a, b / 2, m); //否则是奇数情况
return temp * temp % m;
}
}
Complete code:
#include<algorithm>
#include <iostream>
#include<string.h>
using namespace std;
typedef long long ll;
ll binaryPow(ll a, ll b, ll m)
{
if (b == 0) return 1;
if (b % 2 == 1) return a * binaryPow(a, b - 1, m) % m;
else {
ll temp = binaryPow(a, b / 2, m);
return temp * temp % m;
}
}
int main()
{
//求a的b次幂取余m
ll a, b, m;
cin >> a >> b >> m;
cout << binaryPow(a, b, m);
return 0;
}