快速幂取模

快速幂取模

用法:用于求解 a 的 b 次方,而b是一个非常大的数,用O(n)的复杂度会超时。那么就需要这个算法,注意它不但可以对数求次幂,而且可用于矩阵快速幂。

假如求 x ^ n 次方

我们可以把 n 表示为 2^k1 + 2k2  + 2^k3....,可以证明所有数都可以用前式来表示。(其实就是二进制表示数的原理)

那么 x^n = x^2^k1 * x^2^k2 * x^2^k3......

那么就可以利用二进制来加快计算速度了。

假如 x^22 , 22转化为二进制为 10110, 即 x^22 = x^16 * x^4 * x^2;

那么是不是可以在O(logn)的复杂度求解。

 

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include<vector>
#include<algorithm>

using namespace std;
typedef long long LL;

const int maxn=100007;
const int INF=0x3f3f3f3f;
const int mod=1000003;
LL fun(LL x, LL n)
{
    LL res=1;

    while(n>0)
    {
        if(n & 1)
            res=(res*x)%mod;
        x=(x*x)%mod;
        n>>=1;
    }
    return res;
}

int main()
{
    LL x, n;

    while(~scanf("%lld %lld", &x, &n))
    {
        printf("%lld\n", fun(x, n));
    }
    return 0;
}

 

 

 

posted @ 2016-08-11 09:58  爱记录一切美好的微笑  阅读(126)  评论(0编辑  收藏  举报