首页 > 其他 > 详细

快速幂取模

时间:2014-04-22 14:48:26      阅读:372      评论:0      收藏:0      [点我收藏+]

快速幂取模:

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


快速幂取模,布布扣,bubuko.com

快速幂取模

原文:http://blog.csdn.net/u013081425/article/details/24292371

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!