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

前端 未结 3 1806
傲寒
傲寒 2020-12-11 06:58

what is the fastest method to calculate this, i saw some people using matrices and when i searched on the internet, they talked about eigen values and eigen vectors (no idea

相关标签:
3条回答
  • 2020-12-11 07:44

    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
    
    0 讨论(0)
  • 2020-12-11 07:45
    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.

    0 讨论(0)
  • 2020-12-11 07:56

    C code for calculating 2^n

        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;
        }
    
    0 讨论(0)
提交回复
热议问题