46 字
1 分钟
快速幂
我的代码:
#include <bits/stdc++.h>using namespace std;#define int long longint 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 longint 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);}更推荐的写法
int quickpower(int a,int b,int p){ int res=1%p; while(b){ if(b&1)res=res*a%p; a=a*a%p; b>>=1; } return res;}//可__int128优化 分享
如果这篇文章对你有帮助,欢迎分享给更多人!
部分信息可能已经过时
相关文章 智能推荐
1
素数判定算法
算法 从试除法到 Miller-Rabin,ACM 中判定素数的全套武器——试除、筛法、概率判定,以及什么时候该用哪个
2
纯新手入门 Agent 编程(Vibe Coding)指南——从零搭建你的 AI 编程助手
教程 零基础新手如何用 Cherry Studio + DeepSeek 搭建 AI Agent 编程环境,实现 Vibe Coding(氛围编程)——一种面向结果的自然语言编程方式。从 Git 安装到 Agent 配置,完整图文教程。
3
贡献法学习笔记
算法 从史莱姆困难版学到的贡献法——换一个问题,交换求和顺序,是ACM从铜牌迈向银牌的核心思维模式
4
Lenovo Legion Q7CN 风扇控制协议 — 完整逆向记录
硬件 逆向 Lenovo Legion Pro 7 (Gen 10, Q7CN BIOS) 风扇控制协议全过程。从 USBPcap 抓包失败到 WMI 缓冲区破解,最终实现在 Linux 上控制三风扇曲线。含完整协议格式、Windows/Linux 实现代码。
5
ST 表(Sparse Table)
算法 区间最值查询(RMQ)的倍增解法,Sparse Table 原理与模板
