2020.12.30开始学习AcWing算法《算法竞赛进阶指南》;
在CSDN上传博客方便复习。
//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;
}
然而这样写,如果输入123456789 0 1
答案就会错误,原因是b = 0,不会进入循环,所以要先给ans%c。
AC代码:
//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;
}