Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Created December 17, 2017 13:47
Show Gist options
  • Save bgadrian/3fa283fbfaeeac3a85e9a022eac3ca49 to your computer and use it in GitHub Desktop.
Save bgadrian/3fa283fbfaeeac3a85e9a022eac3ca49 to your computer and use it in GitHub Desktop.
Fibonacci in Go
func TestFibonacci(t *testing.T) {
f := func(n int) (r int) {
a, b := 0, 1
for i := 2; i <= n; i++ {
b, a = a+b, b
}
return b
}
table := []int{1, 3, 8, 13, 21}
res := []int{1, 2, 21, 233, 10946}
//or check if n is a Fibonacci number if and only if either 5n^2 + 4 or 5n^2 - 4 is a perfect square.
for i, n := range table {
r := f(n)
if r != res[i] {
t.Errorf("wrong results got %v want %v", r, res[i])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment