快速幂及相关扩展
//递归
#include<iostream>
using namespace std;
const int maxn = 1e5+5;
typedef long long ll;
ll fastpow(ll a , ll n){
if(n==1) return a;
ll temp = fastpow(a,n/2);
if(n%2==1) //如果n是奇数,n/2向下取整,则会使得a少乘一个次方
return temp*temp*a;
else
return temp*temp;
}
int main(){
ll a,n;
cin>>a>>n;
cout<<fastpow(a,n);
return 0;
}
//位运算
#include<iostream>
using namespace std;
const int maxn =1e5+5;
typedef long long ll;
int fastpow(ll a, ll n){
ll res=1;
ll base=a;
while(n){
if(n&1)
res*=base;
base*=base;
n>>=1;
}
return res;
}
int main()
{
ll a,n;
cin>>a>>n;
cout<<fastpow(a,n);
return 0;
}
//快速幂取模
#include<iostream>
using namespace std;
typedef long long ll;
ll perm(int a,int n,int mod){
ll temp= a;
ll res = 1;
while(n){
if(n&1)
res=(res*temp)%mod;
temp=(temp*temp)%mod;
n>>=1;
}
return res;
}
int main()
{
int a,n,mod;
cin>>a>>n>>mod;
cout<<perm(a,n,mod);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】