In this problem, you are asked to help us develop a method to compute the n-th term, Fn, of the fibonacci sequence. The fibonacci sequence is a recursive sequence defined as Fi=Fi-1+Fi-2, where we let F0=0, F1=1 in this problem. This recursive relation can be written as a matrix multiplication:
and this is the general form of Fn and Fn+1:
This problem is a partial judge problem. You are asked to design a function to calculate (Ab % m) where A is a 2x2 matrix and b,m are integers. Then, using your function and the matrix equation above, we are able to compute our desired Fn of the fibonacci sequence. For the details, please check the main() function carefully.
Given integers a, b and m, calculating the answer of (ab % m) may be trivial for you because it can be solved by using a single for loop:
, or a recursive way:
However, this isn't the best way to do so since its time complexity is O(b). In other words, it requires b times of steps, so it may not be able to finish the task in a second if b is large (e.g. b <= 1018).
Therefore, we have another better algorithm to achieve it. Define a function P(a,b)=ab. For P(a,b), we don't need the answer of P(a, b-1). Instead, we are interested in the answer of P(a, b/2). To explain why, we discuss in two cases of P(a,b):
The code below is a demonstration of this simple algorithm.
Next, we want to analyze the time complexity, or, the steps required to solve this problem. Since pow(a,b) will only call the function pow(a,b/2) once, there're log2(b) of steps. Therefore, the time complexity is O(log(b)), which is much more efficient than the original method O(b).
Note that the following implementation can give the right answer, but the time complexity is still O(b). It is recommended to figure the reason out with your thoughts.
In this problem, for us to compute Fn of the fibonacci sequence, you are asked to design a function to calculate (Ab % m) where A is a 2x2 matrix and b,m are integers.
This function has the following prototype, as declared in function.h:
.
A0=, the 2x2 identity matrix.
The input only consists of two integers n and m, where 0 <= n <= 1018, 0 < m <=2*109.
Output Fn % m in a single line.