Skip to content

Instantly share code, notes, and snippets.

@gaurav-gogia
Created May 29, 2018 08:56
Show Gist options
  • Save gaurav-gogia/9af06f86fb6d249e177a8bf0f8684169 to your computer and use it in GitHub Desktop.
Save gaurav-gogia/9af06f86fb6d249e177a8bf0f8684169 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func main() {
var n int
fmt.Print("Enter Number: ")
fmt.Scanln(&n)
fmt.Print("\nLoading....\n\n")
start := time.Now()
fmt.Println("Bottom Up: ", fib(n))
fmt.Print(time.Since(start), "\n\n")
start = time.Now()
fmt.Println("Memoization: ", fibMemo(n))
fmt.Print(time.Since(start), "\n\n")
start = time.Now()
fmt.Println("Recursion: ", fibRecur(n))
fmt.Println(time.Since(start))
fmt.Println()
}
func fibRecur(n int) int {
var result int
if n == 1 || n == 2 {
result = 1
} else {
result = fibRecur(n-1) + fibRecur(n-2)
}
return result
}
func fibMemo(n int) int {
var result int
var memo []int
if n <= len(memo) {
if n == memo[n] {
return memo[n]
}
}
if n == 1 || n == 2 {
result = 1
} else {
result = fibMemo(n-1) + fibMemo(n-2)
memo = append(memo, result)
}
return result
}
func fib(n int) int {
if n == 1 || n == 2 {
return 1
}
var bottomUp []int
bottomUp = append(bottomUp, 0)
bottomUp = append(bottomUp, 1)
bottomUp = append(bottomUp, 1)
for i := 3; i <= n; i++ {
bottomUp = append(bottomUp, bottomUp[i-1]+bottomUp[i-2])
}
return bottomUp[n]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment