MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Matrix

Function Matrix

math/fibonacci/fibonacci.go:17–40  ·  view source on GitHub ↗

Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form)

(n uint)

Source from the content-addressed store, hash-verified

15
16// Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form)
17func Matrix(n uint) uint {
18 a, b := 1, 1
19 c, rc, tc := 1, 0, 0
20 d, rd := 0, 1
21
22 for n != 0 {
23 if n&1 == 1 {
24 tc = rc
25 rc = rc*a + rd*c
26 rd = tc*b + rd*d
27 }
28
29 ta := a
30 tb := b
31 tc = c
32 a = a*a + b*c
33 b = ta*b + b*d
34 c = c*ta + d*c
35 d = tc*tb + d*d
36
37 n >>= 1
38 }
39 return uint(rc)
40}
41
42// Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio)
43// Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers

Callers 2

TestMatrixFunction · 0.70
BenchmarkMatrixFunction · 0.70

Calls

no outgoing calls

Tested by 2

TestMatrixFunction · 0.56
BenchmarkMatrixFunction · 0.56