Skip to content

Instantly share code, notes, and snippets.

@I159
Last active October 3, 2017 14:54
Show Gist options
  • Save I159/7d11780c8cba65f66e0fede6b66cf067 to your computer and use it in GitHub Desktop.
Save I159/7d11780c8cba65f66e0fede6b66cf067 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
var IDENTITY = [2][2]int64{{1, 0}, {0, 1}}
var DEFAULT = [2][2]int64{{1, 1}, {1, 0}}
func dotProduct(a, b [2][2]int64) (res [2][2]int64) {
for i := 0; i <= 1; i++ {
for j := 0; j <= 1; j++ {
for l := 0; l <= 1; l++ {
res[i][j] += a[i][l] * b[l][j]
}
}
}
return
}
func fiboMatrix(n int) (m [2][2]int64) {
if n > 1 {
m = dotProduct(fiboMatrix(n / 2), fiboMatrix(n / 2))
if (n % 2) > 0 {
m = dotProduct(DEFAULT, m)
}
} else if n == 0 {
m = IDENTITY
} else {
m = DEFAULT
}
return
}
func trippleFibo(n int) (res [3]int64) {
m := fiboMatrix(n)
res[0] = m[1][1]
res[1] = m[0][1]
res[2] = m[0][0]
return
}
func main() {
fmt.Println(trippleFibo(10))
}
@I159
Copy link
Author

I159 commented Oct 3, 2017

Matrix exponentiation Fibonacci series computation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment