Last active
December 20, 2015 01:08
-
-
Save elreimundo/6046360 to your computer and use it in GitHub Desktop.
Determines if a number is a Fibonacci number by a) determining element in the Fibonacci sequence it would be, based on its size, and b) comparing it to that actual element in the Fibonacci sequence. Couldn't have done this without a recursive formula courtesy of the late Edsgar Dijkstra, http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF foun…
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 is_fibonacci?(num) | |
phi = (1 + 5.0**0.5)/2 | |
which_fib = ((Math.log(num)+Math.log(5.0**0.5)) / Math.log(phi)).round | |
num == fibonacci(which_fib) | |
end | |
def fibonacci(n) | |
if n==0 | |
0 | |
elsif n==1 | |
1 | |
elsif n.odd? | |
(fibonacci(n/2))**2 + (fibonacci(n/2 + 1))**2 | |
else | |
fibonacci(n/2) * (fibonacci(n/2) + fibonacci(n/2 - 1) * 2) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision 2 correctly takes the variable "num" as the argument instead of the original "i"