This is a creation in Article, where the information may have evolved or changed.
Several algorithms for package fib/**fibonacii *///Direct loop calculation of the Func fib (n int) int {f: = [3]int{0, 1, 1} if n < 0 {return-1 } if n < 3 {return f[n]} for I: = 3; I <= N; i++ {f[0], f[1] = f[1], f[2] f[2] = f[0] + f[1]} return f[2]}//slightly modified without any intermediate exchange of data Oh ~~func Fib2 (n int) i NT {f: = [2]int{0, 1} if n < 0 {return-1} if n < 2 {return f[n]} for I: = 2; I <= N; i++ {f[i&1] + = f[(i+1) &1]} return f[n&1]}//recursive algorithm, inefficient func fibrec (n int) int {if n < 0 { Return-1} return Fib_recursion (n)}func fib_recursion (n int) int {if n < 3 {return 1} RE Turn fib_recursion (n-1) + fib_recursion (n-2)}//tail recursive algorithm func fibtail (n int) int {if n < 0 {return-1} if N < 3 {return 1} return Fib_tail_recursion (n, 1, 1, 3)}func fib_tail_recursion (n int, a int, b int, beg in int) int {if n = = begin {return a + B} retuRN fib_tail_recursion (n, b, A+b, begin+1)} Unit Test test Code:
Package Fibimport ( //"FMT" "testing") Func Testfib (t *testing. T) { N: = ten F: = Fib (n) if f ! = T.error ("Fib () failed. Got ", F," expected ") }}func TestFib2 (t *testing. T) { N: = ten F: = FIB2 (n) if f ! = T.error ("Fib2 () failed. Got ", F," expected ") }}func Testfibrec (t *testing. T) { N: = ten F: = Fibrec (n) if f ! = T.error ("Fibrec () failed. Got ", F," expected ") }}func testfibtail (t *testing. T) { N: = ten F: = Fibtail (n) if f ! = T.error ("Fibtail () failed. Got ", F," expected ") }}func Benchmarkfib (b *testing. b) {for I: = 0; i < B.N; i++ { Fib (}}func) BenchmarkFib2 (b *testing). b) {for I: = 0; i < B.N; i++ { Fib2 (}}func) Benchmarkfibtail (b *testing). B) {for I: = 0; i < B.N; i++ { fibtail (+) }}
Direct recursion is too slow to test performance.
The
can be seen as a straightforward calculation, with no switching algorithm being the fastest.