UVa 10870

The problem states about a recurrence function of the form: f(n)=a1*f(n-1)+a2*f(n-2)+a3*f(n-3)+...+ad*f(n-d), where n>d. we have to find out the nth term of the sequence modulo m. a1,a2,..,ad given. f(1), f(2),.., f(d) also given. Value of m also given.

Explanation
As value of n given in input lies in the range [1,2^21-1] we can't simply iterate upto n. The idea is to take power of square matrix in action. As, we can get Matrix^power in log2(power) steps, this will be efficient approach though. We can create square matrix of the following form [0 0 0 0 a5] for a d=5. we shall use one more matrix of size 1Xd which will hold [f(1) f(2) f(3) f(4) f(5)] for d=5;                                   |1 0 0 0 a4| Let it be G=  |0 1 0 0 a3| |0 0 1 0 a2| [0 0 0 1 a1] To get value of the nth term, we calculate G^(n-1) first, Let it be G_n-1. Then we multiply first column of G_n-1 to 1xd matrix [f(1) f(2) ... f(d)]. That will be value of nth term for the given sequence.

Gotchas
Value of d<=15 given in constrain of question. But in some inputs of UDebug, it is upto 16. So, better keep the max size of matrix upto 20 or more. So that program be feasible for those also.

Implementations
Notes/Hints on actual implementation here.

Optimizations
Optimizations here.

Input
6 345 443 999999 12434 34234 3435 4566 2124 7676 435 34 78 34 23

10 4895 23123 9999 12244 321743 3412 12156 3424 235555 76 222 12213 7676 435 34 78 34 23 456 8979 2323 2345

1 3455 1007 17 23

0 0 0

Output
316 6332 875