From 1b2e4f26cc6b486518c29f57c32e4569bb798e4d Mon Sep 17 00:00:00 2001 From: K <774162+kaseea@users.noreply.github.com> Date: Sun, 21 Apr 2019 19:48:13 -0700 Subject: [PATCH] pretty basic answer --- lib/fibonacci.rb | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 606755b..0a51bcb 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -5,8 +5,18 @@ # .... # e.g. 6th fibonacci number is 8 -# Time complexity: ? -# Space complexity: ? +# Time complexity: 0(n), where the program only loops through it n times (well, n - 2 times because the first few things are hardcoded cases), was wondering if it was better to do it with recursion? but that would run it with recursion instead of saving everything in an array and indexing it, but I think that would run more times? +# Space complexity: constant, although you have to initialize space for an array + def fibonacci(n) - raise NotImplementedError + raise ArgumentError if n == nil || n < 0 + return 0 if n == 0 + return 1 if n == 1 + arr = [0, 1] + i = 1 + until i == n + arr[i + 1] = arr[i] + arr[i - 1] + i += 1 + end + return arr[i] end