Skip to content

Instantly share code, notes, and snippets.

@memochou1993
Created March 6, 2020 09:29
Show Gist options
  • Save memochou1993/f88b675d4833bb10c966fae7ba9cd477 to your computer and use it in GitHub Desktop.
Save memochou1993/f88b675d4833bb10c966fae7ba9cd477 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
func main() {
fmt.Println(fibonacci1(10)) // 55
fmt.Println(fibonacci2(10)) // 55
fmt.Println(fibonacci3(10)) // 55
}
func fibonacci1(n int) int {
a, b := n%2, 1
for i := 0; i < n/2; i++ {
a += b
b += a
}
return a
}
func fibonacci2(n int) int {
if n < 2 {
return n
}
a, b := 0, 1
for i := 0; i < n; i++ {
next := a + b
a, b = b, next
}
return a
}
func fibonacci3(n int) int {
if n < 2 {
return n
}
return fibonacci3(n-2) + fibonacci3(n-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment