From b69f47912fc5ddc72769d10371166088dc328b3e Mon Sep 17 00:00:00 2001 From: Vivek Patel Date: Sat, 17 Dec 2022 03:33:09 -0800 Subject: gofib --- entries/vivkpatl/gofib.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 entries/vivkpatl/gofib.go (limited to 'entries') diff --git a/entries/vivkpatl/gofib.go b/entries/vivkpatl/gofib.go new file mode 100644 index 0000000..293beaf --- /dev/null +++ b/entries/vivkpatl/gofib.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" +) + +func main() { + var n int + + fmt.Printf("Gimme an int: ") + + _, err := fmt.Scanf("%d", &n) + if err != nil { + panic(err) + } + + if n <= 0 { + panic("n must be greater than 0!") + } + + cache := make([]int, n + 1) + for i := 0; i <= n; i++ { + cache[i] = -1; + } + + fmt.Printf("fib(%d) = %d\n", n, fib(n, cache)) +} + +func fib(n int, cache []int) int { + if n < 2 { + return n + } + + if (cache[n] != -1) { + return cache[n] + } + + cache[n] = fib(n - 1, cache) + fib(n - 2, cache) + + return cache[n] +} -- cgit v1.2.3-70-g09d2