Skip to content

Instantly share code, notes, and snippets.

@GZShi
Created July 28, 2014 09:53
Show Gist options
  • Save GZShi/48ae57990a4eb96b6e0d to your computer and use it in GitHub Desktop.
Save GZShi/48ae57990a4eb96b6e0d to your computer and use it in GitHub Desktop.
斐波那契通项公式
function mulMatrix(a, b) {
return [
a[0]*b[0] + a[1]*b[2],
a[0]*b[1] + a[1]*b[3],
a[1]*b[0] + a[3]*b[2],
a[1]*b[1] + a[3]*b[3]
];
}
function powMatrix(a, n) {
var b = a;
for(var i = 1; i < n; ++i) {
b = mulMatrix(b, a);
}
return b;
}
function fibonacci(n) {
if(n < 3) return 1;
var matrix = powMatrix([0, 1, 1, 1], n - 2);
return matrix[1] + matrix[3];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment