Sauron Eye | Solve programming problems on HackerEarth
Gandalf the Grey is in trouble as Saurons eye Rearrived in the middle world. Now he has to prepare for the war, But in order to defeat Sauron he has to know the power of saurons eye on the day in which he wants to attack.
According to the Elves(Good Friends of Gandalf),Gandalf came to know that saurons eye power on current day is equal to 3 time to its power on previous day minus the power on a day before previous day.
Now Gandalf ask Frodo to give him the power of the Saurons Eye on nth day, but poor Frodo is not good in mathematics so he ask for help from you.
Given the nth day you have to give Frodo power of Saurons eye on that day mod 109 + 7.
Note You can assume the power of sauron eye is 1 on 1st day
and 3 on 2nd day.
f(n)= 3*f(n-1)-f(n-2);
This can be solved using matrix exponentiation as recurrance matrix
[3 -1 ]
[1 0 ]
you can read about matrix exponentiation here
http://zobayer.blogspot.in/2010/11/matrix-exponentiation.html
https://www.hackerearth.com/submission/1950666/
Gandalf the Grey is in trouble as Saurons eye Rearrived in the middle world. Now he has to prepare for the war, But in order to defeat Sauron he has to know the power of saurons eye on the day in which he wants to attack.
According to the Elves(Good Friends of Gandalf),Gandalf came to know that saurons eye power on current day is equal to 3 time to its power on previous day minus the power on a day before previous day.
Now Gandalf ask Frodo to give him the power of the Saurons Eye on nth day, but poor Frodo is not good in mathematics so he ask for help from you.
Given the nth day you have to give Frodo power of Saurons eye on that day mod 109 + 7.
Note You can assume the power of sauron eye is 1 on 1st day
and 3 on 2nd day.
As you have rightly identified given n solution is
f(n)= 3*f(n-1)-f(n-2);
This can be solved using matrix exponentiation as recurrance matrix
[3 -1 ]
[1 0 ]
you can read about matrix exponentiation here
http://zobayer.blogspot.in/2010/11/matrix-exponentiation.html
https://www.hackerearth.com/submission/1950666/
- static int mod = (int)(1E9 + 7);
- static long fib(long n)
- {
- long F[][] = {{3,-1},{1,0}};
- if (n == 0)
- return 0;
- else if(n==1)
- return 1;
- power(F, n-1);
- return F[0][0];
- }
- /* Optimized version of power() in method 4 */
- static void power(long F[][], long n)
- {
- if( n == 0 || n == 1)
- return;
- long M[][] = {{3,-1},{1,0}};
- power(F, n/2);
- multiply(F, F);
- if (n%2 != 0)
- multiply(F, M);
- }
- static void multiply(long F[][], long M[][])
- {
- long x = ((F[0][0]*M[0][0])%mod + (F[0][1]*M[1][0])%mod)%mod;
- long y = ((F[0][0]*M[0][1])%mod + (F[0][1]*M[1][1])%mod)%mod;
- long z = ((F[1][0]*M[0][0])%mod + (F[1][1]*M[1][0])%mod)%mod;
- long w = ((F[1][0]*M[0][1])%mod + (F[1][1]*M[1][1])%mod)%mod;
- F[0][0] = x;
- F[0][1] = y;
- F[1][0] = z;
- F[1][1] = w;
- }