Created
October 26, 2013 21:41
-
-
Save cnocon/7174897 to your computer and use it in GitHub Desktop.
Iterative Solution to the Problem of Determining Whether a Number is a Fibonacci Number or Not
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?(input_num) | |
| raise ArgumentError.new("Number must be greater than or equal to zero.") if input_num < 0 | |
| # we start with these variable values to generate our array of fibonacci nums | |
| fibonacci_nums = [0,1] | |
| i = 1 | |
| # we start with zero because this value is immediately changed in the first iteration and then incremented | |
| # it only has to be less than the input_num so the loop runs at least once | |
| current_fib_num = 0 | |
| until current_fib_num > input_num | |
| next_fib_num = fibonacci_nums[i] + fibonacci_nums[i-1] | |
| fibonacci_nums.push(next_fib_num) | |
| i += 1 | |
| current_fib_num = next_fib_num | |
| end | |
| # here's our iterative solution | |
| fibonacci_check = false | |
| fibonacci_nums.each do |val| | |
| if val.to_i == input_num | |
| fibonacci_check = true | |
| end | |
| end | |
| fibonacci_check | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment