Author: Arjun Bharat
Tester: Arjun Bharat
Editorialist: Arjun Bharat
Math, modular exponentiation
Given the functional equation f(x+1)=kf(x)+g(x), g(x+1)=kg(x)+f(x), f(0)=2 and g(0)=0, the task
is to find the value of f(n) modulo 1000000007, where n and k are program inputs.
This is achieved by first solving the equations to obtain: f(x)= 2x, if(k=1)
f(x)= (k+1)x + (k-1)x, for k>1.
Then we compute the remainder using fast modular exponentiation which is best suited for the given constraints.
One may either add or subtract the two equations and obtain these following equations:
Thus defining new functions h(x)=f(x)+g(x) and p(x)=f(x)-g(x),
we have p(x)=2(k-1)x, h(x)=2(k+1)x.
Substituting any one of them back will yield f(x+1)=(k+1)f(x)-(k-1)x, and thus
by superposition of the homogeneous and particular solutions to the recursive relation, set
f(x)=a(k+1)x + b(k-1)x</sup, solving gives a=b=1.
Thus we have f(x)=(k+1) + (k-1)x.
Now we proceed to obtain the remainder.
Notice that using a linear recurrence, ans(n)=(k * ans(n-1))%M
is O(n) and will not pass in under one second.
We proceed to use fast modular exponentiation. A brief snippet coded in C++ is highlighted below:
long long fn(long long n,long long k)
long long y = fn(n/2,k);
long long z= fn(n/2,k);
long long ans = fn(n,k+1)+fn(n,k-1);
//This code works even when k=0, as the second call returns 0.
This is O(lg n), a marked improvement.
The trivial solution is to use a linear recurrence as described earlier, which is not suitable based on program constraints.
Manually computing and storing f(x) and g(x) values, with or without modulo is
not advisable due to their large magnitudes, and the linear time complexity involved therein.
AUTHOR’S AND TESTER’S SOLUTIONS:
Author’s solution can be found here: jdoodle.com/a/wPF