Created
February 7, 2018 15:16
-
-
Save tomtsang/cac42705a1985243e732e07e3b661730 to your computer and use it in GitHub Desktop.
fibonacci-use-cache.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" | |
| "time" | |
| ) | |
| const LIM = 41 | |
| var fibs [LIM]uint64 | |
| func main() { | |
| var result uint64 = 0 | |
| start := time.Now() | |
| for i := 0; i < LIM; i++ { | |
| result = fibonacci(i) | |
| fmt.Printf("fibonacci(%d) is: %d\n", i, result) | |
| } | |
| end := time.Now() | |
| delta := end.Sub(start) | |
| fmt.Printf("longCalculation took this amount of time: %s\n", delta) | |
| } | |
| func fibonacci(n int) (res uint64) { | |
| // memoization: check if fibonacci(n) is already known in array: | |
| if fibs[n] != 0 { | |
| res = fibs[n] | |
| return | |
| } | |
| if n <= 1 { | |
| res = 1 | |
| } else { | |
| res = fibonacci(n-1) + fibonacci(n-2) | |
| } | |
| fibs[n] = res | |
| return | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment