Created
September 13, 2014 14:40
-
-
Save 910JQK/13a17ff8d29085ff7bf4 to your computer and use it in GitHub Desktop.
Fibonacci Number (Matrix Algorithm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using std::cin; | |
using std::cout; | |
class Matrix22 { | |
public: | |
int data[2][2]; | |
Matrix22(int a11, int a12, int a21, int a22); | |
Matrix22(const Matrix22 &matrix); | |
Matrix22 power(int n); | |
Matrix22& operator*=(const Matrix22 &target_matrix); | |
}; | |
Matrix22::Matrix22(int a11, int a12, int a21, int a22){ | |
data[0][0] = a11; | |
data[0][1] = a12; | |
data[1][0] = a21; | |
data[1][1] = a22; | |
} | |
Matrix22::Matrix22(const Matrix22 &matrix){ | |
data[0][0] = matrix.data[0][0]; | |
data[0][1] = matrix.data[0][1]; | |
data[1][0] = matrix.data[1][0]; | |
data[1][1] = matrix.data[1][1]; | |
} | |
Matrix22 Matrix22::power(int n){ | |
Matrix22 t(*this); | |
Matrix22 r(1, 0, 0, 1); | |
while(n > 0){ | |
if(n % 2 == 1) | |
r *= t; | |
n /= 2; | |
t *= t; | |
} | |
return r; | |
} | |
Matrix22& Matrix22::operator*=(const Matrix22 &target){ | |
int r[2][2], i, j; | |
for(i=0; i<2; i++) | |
for(j=0; j<2; j++) | |
r[i][j] = data[i][0] * target.data[0][j] + data[i][1] * target.data[1][j]; | |
for(i=0; i<2; i++) | |
for(j=0; j<2; j++) | |
this->data[i][j] = r[i][j]; | |
return *this; | |
} | |
int main(int argc, char *argv[]){ | |
int n; | |
cin >> n; | |
if(n < 2){ | |
if(n == 1) | |
cout << "1\n"; | |
else if(n == 2) | |
cout << "2\n"; | |
return 0; | |
} | |
Matrix22 matrix(1, 1, 1, 0); | |
Matrix22 result = matrix.power(n-2); | |
cout << result.data[0][0] + result.data[0][1] << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No Zuo No Die. Why u Try.
CLASS