Created
January 15, 2014 13:27
-
-
Save mtungusov/8436168 to your computer and use it in GitHub Desktop.
Fibonacci in Go
This file contains hidden or 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 fib(n int) (r int) { | |
| switch n { | |
| case 0: | |
| r = 0 | |
| case 1: | |
| r = 1 | |
| default: | |
| r = fib(n-1) + fib(n-2) | |
| } | |
| return | |
| } | |
| func fib2(n int) (r int) { | |
| r, acc := 0, 1 | |
| for i := 0; i < n; i++ { | |
| r, acc = acc, r+acc | |
| } | |
| return | |
| } | |
| // Fib 3 | |
| func loop(n int) (r, acc int) { | |
| if n > 1 { | |
| r, acc = loop(n - 1) | |
| r, acc = r+acc, r | |
| } else { | |
| r, acc = n, n-1 | |
| } | |
| return | |
| } | |
| func fib3(n int) int { | |
| r, _ := loop(n) | |
| return r | |
| } | |
| func main() { | |
| fmt.Print("Enter num: ") | |
| var input int | |
| fmt.Scanf("%d", &input) | |
| fmt.Printf("Fib(%d) = %d\n", input, fib3(input)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment