From 7b57013dbb71855ed0b157a7758ce72214db831c Mon Sep 17 00:00:00 2001 From: Shamira Date: Sun, 21 Apr 2019 12:14:21 -0700 Subject: [PATCH] Fibonacci with Big O explanations. --- lib/fibonacci.rb | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 606755b..e17139d 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -5,8 +5,19 @@ # .... # e.g. 6th fibonacci number is 8 -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) with n being the input. +# Space complexity: O(1)- constant because it take the same amount of space regardless of the input. def fibonacci(n) - raise NotImplementedError + if n == nil || n < 0 + raise ArgumentError, "n cannot be nill or negaitve" + end + + if n == 1 || n == 2 + result = 1 + elsif n == 0 + result = 0 + else + result = fibonacci(n - 1) + fibonacci(n - 2) + end + return result end