快速幂

比普通幂运算更快,只需要预处理一些数就可以

普通幂:

 

1     int res=1;
2 for(int i=0;i<k;i++) 
3     res=res*n; 
4         return res;

快速幂:

//快速幂:https://www.luogu.com.cn/problem/P1226
#include <bits/stdc++.h>
//#define int long long
using namespace std;
const int N=1e5+10,mod=1e9+7;
string s;
long long n,t,f[N],res,num,ans,k,m;
bool vis[N];
//a^b%k
long long qpow(long long a,long long b,long long k)
{
    res=1;
    while(b){
        if(b&1) res=res*a%k;
        b>>=1,a=a*a%k;
    }
    return res;
}
int main()
{
    std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    cin>>n>>m>>k;
    cout<<n<<'^'<<m<<" mod "<<k<<"="<<qpow(n,m,k)<<endl;
    return 0;
}

 

posted @ 2023-06-21 14:25  o-Sakurajimamai-o  阅读(20)  评论(0)    收藏  举报
-- --