diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 606755b..86698c1 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -5,8 +5,23 @@ # .... # e.g. 6th fibonacci number is 8 -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n), n is the number of computations this calculation needs to run to compute the nth fibonacci number +# Space complexity: O(1), space complexity is constant because this method only require a storage for 3 variables (p,p1,p2) regardless of number of operations def fibonacci(n) - raise NotImplementedError + if n.nil? || n < 0 + raise ArgumentError + end + if n == 0 + return 0 + else + p1 = 0 + p2 = 1 + + (n - 1).times do + p = p1 + p2 + p1 = p2 + p2 = p + end + return p2 + end end