how to calculate 2^n modulo 1000000007 , n = 10^9

蹲街弑〆低调 提交于 2019-11-28 12:28:38
f(n) = (2*f(n-1)) + 2 with f(1)=1

is equivalent to

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

so that finally

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

where you can then apply fast modular power methods.

Modular exponentiation by the square-and-multiply method:

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
//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;   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!