快速幂及相关扩展

//递归

#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;
}

 

posted @   ganl啦  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示