快速幂取模

来源:互联网 发布:卡乐比麦片辐射 知乎 编辑:程序博客网 时间:2024/05/29 03:08

快速幂取模,即求a的n次方再取模,如果n很大,时间开销会很大

其原理是以下两个明显的公式:
这里写图片描述

代码如下:

#include <bits/stdc++.h>using namespace std;typedef long long LL;const int MOD=1000009;LL powerMod(LL a,LL n){    LL res=1;    while(n){        if(n%2)            res=res*a%MOD;        n/=2;        a=a*a%MOD;    }    return res;}int main(){    LL a,n;    while(cin>>a>>n){        LL res=powerMod(a,n);        cout<<res<<endl;    }    return 0;}

时间复杂度为O(logn)。

0 0
原创粉丝点击