Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Last active December 20, 2015 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elreimundo/6046360 to your computer and use it in GitHub Desktop.
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…
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
@elreimundo
Copy link
Author

Revision 2 correctly takes the variable "num" as the argument instead of the original "i"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment