That deed POJ3070 Fibonacci number column of rapid power recursive matrix template title

Topic analysis:

For n given, calculated Fibonacci number 4 last number of n items, when a large n when ordinary recursion timeout, presented here fast power matrix to solve a lot of times when recurrence As a result, the matrix has been given here, can be calculated directly

. 1 #include <the iostream>
 2 #include <stdio.h>
 . 3  the using  namespace STD;
 . 4  
. 5  const  int MOD = 10000 ;
 . 6  struct MAT {
 . 7      int m [ 2 ] [ 2 ];
 . 8  };
 . 9  
10 MAT operator * ( A MAT, MAT B) {         // overloaded multiplication sign, while the data mod10000 
. 11      MAT RET;
 12 is      for ( int I = 0 ; I < 2 ; I ++ ) {
 13 is         for(int j = 0; j < 2; j++){
14             long long temp = 0;
15             for(int k = 0; k < 2; k++){
16                 temp += a.m[i][k] * b.m[k][j];
17                 temp %= mod;
18             }
19             ret.m[i][j] = temp;
20         }
21     }    
22     return ret;
23 }
24 
25 MAT pow_mat (MAT A, int n-) {         // matrix Fast Power and fast power identical (thought generalized fast exponentiation) 
26 is      MAT RES = A;
 27      the while (n-) {
 28          IF (n-& . 1 ) RES = RES * A ;
 29          A = A * A;
 30          n->> = . 1 ;
 31 is      }
 32      return RES;
 33 is  }
 34 is  
35  int main () {
 36      int n-;
 37 [      the while (Scanf ( " % D " !, & n-) = the EOF) {
38 is          IF (n-== - . 1 ) BREAK ;
 39          IF (n-== 0 ) the printf ( " 0 \ n- " );
 40          the else  IF (n-== . 1 ) the printf ( " . 1 \ n- " );
 41 is          the else  IF ( == n- 2 ) the printf ( " . 1 \ n- " );
 42 is          the else {
 43 is              MAT a;                             // Construct a matrix initial n-2 which is a power of m [0] [0] is the desired answer 
44 is              AM [ 0 ] [ 0] = . 1 ;
 45              AM [ 0 ] [ . 1 ] = . 1 ;
 46 is              AM [ . 1 ] [ 0 ] = . 1 ;
 47              AM [ . 1 ] [ . 1 ] = 0 ;
 48              MAT ANS = pow_mat (A, N- 2 );         // call the fast exponentiation matrix 
49              the printf ( " % D \ n- " , ans.m [ 0 ] [ 0 ]);
 50          }
 51 is      }
 52 is     return 0;
53 }

 

Guess you like

Origin www.cnblogs.com/findview/p/11805411.html