Created
March 6, 2020 09:29
-
-
Save memochou1993/f88b675d4833bb10c966fae7ba9cd477 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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