40 字
1 分钟
快速幂
2026-05-29
无标签

我的代码:

#include <bits/stdc++.h>
using namespace std;
#define int long long
int a, b, p;
int po(int x, int y)
{
    if (y == 0)
        return 1;
    if (y == 1)
        return x;
    if (y % 2 == 0)
        return (po(x, y / 2) % p) * (po(x, y / 2) % p);
    else
        return (po(x, y / 2) % p) * (po(x, y / 2) % p) * (x % p);
}
signed main()
{
    cin >> a >> b >> p;
    int ans=po(a, b) % p;
    printf("%lld^%lld mod %lld=%lld", a, b, p, ans);
}

==这里每次递归都会调用两次po,会重复算两次导致超时,注意==

最好这么写:

#include <bits/stdc++.h>
using namespace std;
#define int long long
int a, b, p;
int po(int x, int y)
{
    if (y == 0)
        return 1;
    if (y == 1)
        return x%p;
  int half = po(x, y / 2) % p;
    if (y % 2 == 0)
        return (half*half % p);
    else
        return half*half * (x % p)%p;//注意这里half完了也要取模,这段代码没取是错的
}
signed main()
{
    cin >> a >> b >> p;
    int ans=po(a, b) % p;
    printf("%lld^%lld mod %lld=%lld", a, b, p, ans);
}
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

快速幂
https://caoyue.xin/posts/quickpower/
作者
Colton/曹越
发布于
2026-05-29
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录