Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 about this stuff)...there was a question which reduced to a recursive equation f(n) = (2*f(n-1)) + 2 , and f(1) = 1, n could be upto 10^9.... i already tried using DP, storing upto 1000000 values and using the common fast exponentiation method, it all timed out im generally weak in these modulo questions, which require computing large values

like image 452
manu4rhyme Avatar asked Sep 30 '22 17:09

manu4rhyme


1 Answers

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.

like image 79
Lutz Lehmann Avatar answered Oct 04 '22 19:10

Lutz Lehmann