快速幂取模

快速幂取模:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值