diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..2415499 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -1,8 +1,22 @@ # Improved Fibonacci -# Time Complexity - ? -# Space Complexity - ? (should be O(n)) +# Time Complexity - O(n) +# Space Complexity - O(n) stack space # Hint, you may want a recursive helper method def fibonacci(n) - + return fib_helper([0, 1], 2, n) end + +def fib_helper(results, current, n) + raise ArgumentError if n < 0 + return results[n] if n == 0 || n == 1 + + if current == n + return results[0] + results[1] + end + + temp = results[0] + results[1] + results[0] = results[1] + results[1] = temp + return fib_helper(results, current + 1, n) +end \ No newline at end of file diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..a21339d 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,15 +1,24 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(logn) n is the number itself +# Space Complexity - O(logn) def super_digit(n) - + return n if n/10 == 0 + + sum = n % 10 + while n/10 != 0 + n = n/10 + sum += n % 10 + end + return super_digit(sum) end - -# Time Complexity - ? -# Space Complexity - ? + +# Time Complexity - O(logn) n is the number itself +# Space Complexity - O(logn) def refined_super_digit(n, k) - + return n if k == 1 && n/10 == 0 + sum = 0 + sum += super_digit(n) * k + return super_digit(sum) end - \ No newline at end of file diff --git a/test/super_digit_test.rb b/test/super_digit_test.rb index 60da3a1..8eb6475 100644 --- a/test/super_digit_test.rb +++ b/test/super_digit_test.rb @@ -1,6 +1,6 @@ require_relative "test_helper" -xdescribe "super_digit" do +describe "super_digit" do it "will return 2 for super_digit(9875)" do # Act answer = super_digit(9875)