Question: Can you obtain the nth Fibonacci number? 0 <n <maxlongint
The output result mod32768 is too large.
Idea: Generally, the methods for finding the Fibonacci series are recursive, dynamic, or rolling optimization, but the space or time complexity is too high, now there is an optimization algorithm that uses a matrix plus a rapid power to maintain the time complexity in logn.
Initialize a 2 × 2 matrix. If the initial value is {,}, it indicates {A2, A1, A1, a0}. After the square of this matrix is obtained, {2, 1, 1, 0} represents {A3, A2, A2, A1} respectively, so that the law can be obtained. In fact, this algorithm is mainly optimized on the fast power. As for the matrix, the storage format is different.
Code:
# Include <iostream> using namespace STD; // matrix struct MTA {int A [2] [2] ;}; // multiply the matrix, A * B mta mul (mta a, mta B) {mta c; For (INT I = 0; I <2; I ++) {for (Int J = 0; j <2; j ++) {C. A [I] [J] = 0; For (int K = 0; k <2; k ++) {C. A [I] [J] + = (. A [I] [k] * B. A [k] [J]) % 32768 ;}} return C ;}int main () {int N; MTA res; MTA base; // calculate the nth Fibonacci number while (CIN> N) {res. A [0] [0] = 1; Res. A [0] [1] = 0; Res. A [1] [0] = 0; Res. A [1] [1] = 1; base. A [0] [0] = 1; base. A [0] [1] = 1; base. A [1] [0] = 1; base. A [1] [1] = 0; // matrix fast power while (n! = 0) {If (N & 1) {res = MUL (Res, base) ;}base = MUL (base, base); N/= 2 ;} cout <res. A [0] [1] <Endl;} return 0 ;}