Created
August 16, 2013 04:10
-
-
Save alexanderlarson/6247243 to your computer and use it in GitHub Desktop.
Recursive (slow) solution to Fibonacci validation exercise
This file contains 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 fibonacci(n) | |
if n <= 1 | |
n | |
else | |
fibonacci(n-1) + fibonacci(n-2) | |
end | |
end | |
def isFibonacci(soughtNumber) | |
return isFibonacci?(soughtNumber, 1) | |
end | |
def isFibonacci?(soughtNumber, currentFibonacciIndex) | |
currentFibonacciNumber = fibonacci(currentFibonacciIndex) | |
isFibonacciNumber = currentFibonacciNumber == soughtNumber | |
if (isFibonacciNumber) | |
return true | |
end | |
outOfRange = currentFibonacciNumber > soughtNumber | |
if (outOfRange) | |
return false | |
end | |
nextFibonacciIndex = currentFibonacciIndex + 1 | |
return isFibonacci?(soughtNumber, nextFibonacciIndex) | |
end | |
#Call 2nd method for Fibonacci verification | |
puts isFibonacci(233) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment