刚开始一直执着于推公式,最后放弃了,打表发现规律是n^k,写个快速幂即可。不过要注意快速幂中的a是long long int类型的,所以要先取模一下。
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
const int MOD = 1e9 + 7;
const int MAX_N = 5e5 + 5;
const int INF = 0x3f3f3f3f;
LL mod_pow(LL a, LL n, LL mod)
{
LL res = 1;
a %= mod; // a要先取模
while (n)
{
if (n & 1)
res = res * a % mod;
a = a * a % mod; // 如果a不先取模,这里会爆long long int
n >>= 1;
}
return res;
}
int main()
{
//freopen("test.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
cin.sync_with_stdio(false);
LL n, k;
int Case = 1;
while (cin >> n >> k)
cout << "Case #" << Case++ << ": " << mod_pow(n, k, MOD) << endl;
return 0;
}
本文介绍了一种通过快速幂算法求解n的k次方的方法。在解决该问题的过程中,作者首先尝试推导公式但未成功,最终通过观察规律得出解法,并特别注意到了在快速幂算法中变量取模的重要性。
610

被折叠的 条评论
为什么被折叠?



