Skip to content

Instantly share code, notes, and snippets.

@bluetwin
Last active December 15, 2015 13:39
Show Gist options
  • Save bluetwin/5268767 to your computer and use it in GitHub Desktop.
Save bluetwin/5268767 to your computer and use it in GitHub Desktop.
Four versions of finding the nth element on the Fibonacci series
# Four versions of the Fibonacci solution for the nth element
# Iterative
def fib(n)
if n < 2
num = n
else
n1 = 1
n2 = 0
n-1.times do |i|
num = n1+n2
n1 = num
n2 = n1
end
end
num
end
# Recursive Big O(2^n) - bi-nomial
def fib_recursive_factorial(n)
if n < 2
n
else
fib_recursive_factorial(n-1) + fib_recursive_factorial(n-2)
end
end
#Recursive Big O(n) - linear
def fib_recursive_linear(n, i=2,n1=1,n2=0)
if n < 2
n
else
if i < n
fib_recursive_linear(n,i+1,n1+n2, n1)
else
n1+n2
end
end
end
# Using phi(Golden ratio) to solve in O(1), but with side effect of rounding
def fib_phi(n)
phi =(1+Math.sqrt(5))/2
phi1 = (1-Math.sqrt(5))/2
(phi**n / Math.sqrt(5) - (1-phi)**n / Math.sqrt(5)).round
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment