Skip to content

Instantly share code, notes, and snippets.

@Bodacious
Created December 9, 2015 18:42
Show Gist options
  • Save Bodacious/bacc186da612185b70bd to your computer and use it in GitHub Desktop.
Save Bodacious/bacc186da612185b70bd to your computer and use it in GitHub Desktop.
Method to return the nth value of the Fibonacci sequence
# PHI - Some greek number
PHI = Rational(610,377).to_f
# Negative inverse of PHI
I_PHI = -Rational(1, PHI).to_f
# Square root of 5
SQRT_5 = 5 ** 0.5
# Fibonacci value for given number x
#
# x - An Integer representing the nth number in the fibonacci sequence
#
# Returns an Integer
def fibonacci(n)
((PHI**n - I_PHI**n) / SQRT_5).round
end
require "rspec"
require "fibonacci"
# Bunch of tests to prove I'm right...
describe "#fibonacci" do
it "returns 0 if x is 0" do
expect(fibonacci(0)).to eql(0)
end
it "returns 1 if x is 1" do
expect(fibonacci(1)).to eql(1)
end
it "returns 1 if x is 2" do
expect(fibonacci(2)).to eql(1)
end
it "returns 2 if x is 3" do
expect(fibonacci(3)).to eql(2)
end
it "returns 3 if x is 4" do
expect(fibonacci(4)).to eql(3)
end
it "returns 5 if x is 5" do
expect(fibonacci(4)).to eql(3)
end
it "returns 34 if x is 9" do
expect(fibonacci(9)).to eql(34)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment