快速幂取模

来源:互联网 发布:厦门seo分享 编辑:程序博客网 时间:2024/06/18 05:10

快速幂取模:

int PowerMod(int a, int b, int c){    int ans = 1;    a = a % c;    while(b>0)    {        if(b&1)            ans = (ans * a) % c;a = (a * a) % c;        b >>= 1;    }    return ans;}



几道模板题:

http://acm.hdu.edu.cn/showproblem.php?pid=1061

求a^b的个位数字,即(a^b)mod 10。

int mod_exp(int a, int b, int c){    int ans = 1;    int t = a%c;    while(b)    {        if(b&1)            ans = ans*t%c;        t = t*t%c;        b >>= 1;    }    return ans;}int main(){    int test,n;    scanf("%d",&test);    while(test--)    {        scanf("%d",&n);        int ans = mod_exp(n,n,10);        printf("%d\n",ans);    }    return 0;}



http://acm.hdu.edu.cn/showproblem.php?pid=2035

求a^b的最后三位数,即(a^b)mod 1000.

using namespace std;const int INF = 0x3f3f3f3f;_LL mod_exp(_LL a, _LL b, int c){    _LL ans = 1;    _LL t = a%c;    while(b)    {        if(b&1)            ans = ans*t%c;        t = t*t%c;        b >>= 1;    }    return ans;}int main(){    _LL a,b;    while(~scanf("%I64d %I64d",&a,&b))    {        if(a == 0 && b == 0) break;        _LL ans = mod_exp(a,b,1000);        printf("%I64d\n",ans);    }    return 0;}



http://poj.org/problem?id=1995

_LL mod_exp(_LL a, _LL b, _LL c){    _LL res = 1;    _LL t = a%c;    while(b)    {        if(b&1)            res = res*t%c;        t = t*t%c;        b >>= 1;    }    return res;}int main(){    int test,t;    _LL ans;    scanf("%d",&test);    while(test--)    {        _LL a,b,c;        ans = 0;        scanf("%I64d",&c);        scanf("%d",&t);        while(t--)        {            scanf("%I64d %I64d",&a,&b);            _LL res = mod_exp(a,b,c);            ans = (ans%c + res%c)%c;        }        printf("%I64d\n",ans);    }    return 0;}


0 0
原创粉丝点击