如何计算2 ^ n modulo 1000000007,n = 10 ^ 9

时间:2014-05-24 15:23:54

标签: math matrix eigenvector eigenvalue exponentiation

计算这个的最快方法是什么,我看到有些人使用矩阵,当我在网上搜索时,他们谈到了特征值和特征向量(不知道这些东西)......有一个问题减少了到一个递归方程 f(n)=(2 * f(n-1))+ 2,f(1)= 1, n可能高达10 ^ 9 .... 我已经尝试使用DP,存储高达1000000的值并使用常见的快速取幂方法,它都超时了 我在这些模数问题中通常很弱,这需要计算大值

3 个答案:

答案 0 :(得分:2)

f(n) = (2*f(n-1)) + 2 with f(1)=1

相当于

(f(n)+2) = 2 * (f(n-1)+2)
         = ...
         = 2^(n-1) * (f(1)+2) = 3 * 2^(n-1)

最后

f(n) = 3 * 2^(n-1) - 2

然后您可以应用快速模块化电源方法。

答案 1 :(得分:1)

通过square-and-multiply方法的模幂运算:

function powerMod(b, e, m)
    x := 1
    while e > 0
        if e%2 == 1
            x, e := (x*b)%m, e-1
        else b, e := (b*b)%m, e//2
    return x

答案 2 :(得分:0)

//Include library

const int mod = 1e9+7;

//Here base is assumed to be 2
int cal_pow(int x){
    int res;
    if (x == 0) res=1;
    else if (x == 1)    res=2;
    else {
        res = cal_pow(x/2);
        if (x % 2 == 0) 
            res = (res * res) % mod;
        else
            res = (((res*res) % mod) * 2) % mod;
    }
    return res;
}

int main(){
    int n, ans;
    cin >> n;
    ans = cal_pow(n);
    cout << ans;
    return 0;   
}
相关问题