aboutsummaryrefslogtreecommitdiff
path: root/entries
diff options
context:
space:
mode:
authorVivek Patel2022-12-17 11:33:09 +0000
committerVivek Patel2022-12-17 11:33:09 +0000
commitb69f47912fc5ddc72769d10371166088dc328b3e (patch)
tree3482e30fa0246bfad61126aa562045b159bc75b8 /entries
parent754ba58f00791f21eaf47a8be085df2bffc857d4 (diff)
gofib
Diffstat (limited to 'entries')
-rw-r--r--entries/vivkpatl/gofib.go41
1 files changed, 41 insertions, 0 deletions
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]
+}