diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..63a8134 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -1,8 +1,18 @@ # Improved Fibonacci +# Time Complexity - O(n) +# Space Complexity - O(n) -# Time Complexity - ? -# Space Complexity - ? (should be O(n)) -# Hint, you may want a recursive helper method def fibonacci(n) - + return fib_helper(0, 1, 2, n) end + +def fib_helper(fib_minus_two, fib_minus_one, current, n) + return n if n == 0 || n == 1 + raise ArgumentError if n < 0 + + if current == n + return fib_minus_one + fib_minus_two + end + + return fib_helper(fib_minus_one, fib_minus_one + fib_minus_two, current + 1, n) +end diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..acec8f1 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,15 +1,38 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(1) <- this doesn't feel quite right but it's definitely not O(n) +# Space Complexity - O(1) <- same here def super_digit(n) - + return super_digit_helper(n.to_s) end + +def super_digit_helper(n) + return n.to_i if n.length == 1 + + sum = 0 + n.each_char do |digit| + sum += digit.to_i + end + + return super_digit_helper(sum.to_s) +end +# Time Complexity - O(1) <- same qualms as above +# Space Complexity - O(1) +# I think I missed the point here, this doesn't seem like it would necessarily involve more time complexity than regular super_digit so I'm not sure how to reduce it -# Time Complexity - ? -# Space Complexity - ? def refined_super_digit(n, k) - + return refined_super_digit_helper(n.to_s * k) +end + +def refined_super_digit_helper(n) + return n.to_i if n.length == 1 + + sum = 0 + n.each_char do |digit| + sum += digit.to_i + end + + return super_digit_helper(sum.to_s) 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)