aboutsummaryrefslogtreecommitdiff
path: root/entries/vivkpatl
diff options
context:
space:
mode:
authorBraxton Hall2022-12-18 16:27:14 +0000
committerGitHub2022-12-18 16:27:14 +0000
commit77e827e1ad5e4598811335e7f0c9bfeb20a425c4 (patch)
tree74f4290f81fd727bcc6c19ece77655958cd80e3e /entries/vivkpatl
parent883f7d6767492bd576f37f2b5fd4ada26e55ac83 (diff)
parent7d6769991b0e62b4cf12766346f7a7df3bc397df (diff)
Merge pull request #95 from vivkpatl/gofib
gofib
Diffstat (limited to 'entries/vivkpatl')
-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]
+}