Created
October 26, 2013 21:56
-
-
Save cnocon/7175055 to your computer and use it in GitHub Desktop.
Recursive Solution to Fibonacci Problem (Using Memoization)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def is_fibonacci?(i) | |
| n = 1 | |
| fib = 1 | |
| while fib <= i | |
| fib = recursive_nth_fibonacci(n) | |
| return true if fib == i | |
| n += 1 | |
| end | |
| false | |
| end | |
| @fib_array = [0, 1, 1] | |
| def recursive_nth_fibonacci(n) | |
| # @fib_array.each do |v| | |
| # #puts "#{v} has an index of #{@fib_array.index(v)}" #puts fibonacci n and if doesn't have, then it caluculates it | |
| # end | |
| @fib_array[n] ||= recursive_nth_fibonacci(n-2) + recursive_nth_fibonacci(n-1) | |
| end | |
| #@fib_array[n] is created and added to fib array | |
| # DRIVER TEST CODE | |
| # This code calls your above methods and passes arguments (input) and equates it to an expectation (output) | |
| # eg puts find_product(10, 3) == 30 | |
| # Include all your tests below: | |
| puts is_fibonacci?(1) == true | |
| puts is_fibonacci?(3) == true | |
| puts is_fibonacci?(21) == true | |
| puts is_fibonacci?(8670007398507948658051921) == true | |
| puts is_fibonacci?(927372692193078999171) == false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment