2020.12.30 Start learning AcWing algorithm "Algorithm Competition Advanced Guide";
upload a blog on CSDN to facilitate review.
//wecccccccc
//2020.12.30
#include <iostream>
using namespace std;
typedef long long int ll;
ll fast_power(ll a, ll b, ll c) {
ll ans = 1;
a %= c;//防止一开始输入的值过大
while (b) {
if (b & 1) {
ans = (ans * a) % c;
}
a = (a * a) % c;
b >>= 1;
}
return ans;
}
int main() {
ll c, b, a, ans1;
cin >> a >> b >> c;
ans1 = fast_power(a, b, c);
cout << ans1 << endl;
return 0;
}
However, if you write 123456789 0 1
The answer will be wrong because b = 0 and will not enter the loop, so give ans%c first.
AC code:
//Wecccccccc
//12.30
#include <iostream>
using namespace std;
typedef long long int ll;
int main()
{
ll a,b,c;
cin>>a>>b>>c;
ll ans = 1 % c;
a %=c;
while (b)
{
if (b&1)
{
ans = (ans * a)%c;
}
a = (a*a)%c;
b>>=1;
}
cout<<ans<<endl;
return 0;
}