Created
April 30, 2012 08:12
-
-
Save spencerdcarlson/2556482 to your computer and use it in GitHub Desktop.
Three different versions of the Fibonacci sequence
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
class Fibonacci | |
def initialize(num) | |
@n = num | |
@info = { | |
"Origional" => num, "Fib" => fib(@n), | |
"FibTwo" => fibTwo(@n), "FibFast" => fibFast(@n) } | |
end | |
def fib(x) | |
if x == 1 || x == 2 then 1 else fib(x-1) + fib(x-2) end | |
end | |
def fibTwo(x) | |
result = 1 ; prev = -1 | |
for i in 0..x do sum = (result + prev ); prev = result; result = sum end | |
result | |
end | |
def fibFast(x) | |
#Gr = Golden Ratio | |
gr = ( 1 + Math.sqrt(5) ) / 2 | |
gr**x / Math.sqrt(5) + 0.5 | |
end | |
def show | |
@info.each do |key,value| | |
puts "#{key}: " + sprintf("%.2f", value) | |
end | |
end | |
end | |
f = Fibonacci.new(20) | |
f.show |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment