diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..2be243a 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -1,8 +1,20 @@ # Improved Fibonacci -# Time Complexity - ? +# Time Complexity - O(n) # 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( solutions, current, n ) + return n if n == 0 || n == 1 + raise ArgumentError if n < 0 + + if current == n + return solutions[n - 1] + solutions[n - 2] + end + + solutions << solutions[current - 1] + solutions[current -2] + return fib_helper(solutions, current + 1, n) end diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..5e3b3e1 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,15 +1,42 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity : O(n), depends on number of digits +# Space Complexity : O(1) as the array of digits will always be same and I will always have same variables (sum, reminder) def super_digit(n) - + + return n if [0,1,2,3,4,5,6,7,8,9].include?(n) == true + + sum = 0 + until n == 0 do + reminder = n % 10 + sum += reminder + n = n/10 + end + + super_digit(sum) end -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(n), depends on number of digits +# Space Complexity : O(1) as the array of digits will always be same and I will always have same variables (sum, reminder, superdigit) def refined_super_digit(n, k) - + + return n if [0,1,2,3,4,5,6,7,8,9].include?(n) == true && k == 1 + + sum = 0 + until n == 0 do + reminder = n % 10 + sum += reminder + n = n/10 + end + + redifined_number = sum * k + refined_super_digit(redifined_number, 1) 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)