题解 | #Fibonacci(矩阵快速幂法)#

Fibonacci

http://www.nowcoder.com/practice/17ad6908e36a49f4b06ea96936e8bb25

#include<iostream>
#include<cstdio>

using namespace std;

const int MAXN = 10;

struct Matrix {
	int row;
	int col;
	int matrix[MAXN][MAXN];
	Matrix() {}
	Matrix(int r,int c):row(r),col(c) {}
};


Matrix Multiple(Matrix x,Matrix y) {
	Matrix answer = Matrix(x.row,y.col);
	for(int i =0; i < x.row; ++i) {
		for(int j = 0; j < y.col; ++j) {
			answer.matrix[i][j] = 0;
			for(int k = 0; k < x.col; ++k) {
				answer.matrix[i][j] += x.matrix[i][k] * y.matrix[k][j];
			}
		}
	}
	return answer;
}


Matrix QuickPower(Matrix x,int n) {   //x^n
	Matrix answer = Matrix(x.row,x.col);
	for(int i = 0; i < x.row; ++i) {
		for(int j = 0; j < x.col; ++j) {
			if(i == j) {
				answer.matrix[i][j] = 1;
			} else {
				answer.matrix[i][j] = 0;
			}
		}
	}
	while(n != 0) {
		if(n % 2 == 1) {
			answer = Multiple(answer,x);
		}
		n /= 2;
		x = Multiple(x,x);
	}
	return answer;
}


int main() {
	int n;
	while(scanf("%d",&n) != EOF) {
		Matrix fibonacci = Matrix(2,2);
		fibonacci.matrix[0][0] = 1;
		fibonacci.matrix[0][1] = 1;
		fibonacci.matrix[1][0] = 1;
		fibonacci.matrix[1][1] = 0;
		Matrix answer = QuickPower(fibonacci,n);
		printf("%d\n",answer.matrix[0][1]);
	}
	return 0;
}
全部评论
太复杂了你想的
点赞 回复 分享
发布于 05-07 09:05 上海

相关推荐

牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
10-11 17:30
湖南大学 C++
我已成为0offer的糕手:羡慕
点赞 评论 收藏
分享
4 收藏 评论
分享
牛客网
牛客企业服务