Skip to content

Instantly share code, notes, and snippets.

@nbkhope nbkhope/factorial.rb
Last active Jul 7, 2016

Embed
What would you like to do?
Introduction to RSpec and Test-Driven Development using Factorial
# Given an integer greater than or equal to zero
def factorial(n)
return 1 if n <= 1
product = 1
index = n
while index > 1
product *= index
index -= 1
end
product
end
require_relative '../factorial'
describe "Factorial" do
it "computes the factorial of 0" do
expect(factorial(0)).to eq 1
end
it "computes the factorial of 1" do
expect(factorial(1)).to eq 1
end
it "computes the factorial of 2" do
expect(factorial(2)).to eq 2
end
it "computes the factorial of 3" do
expect(factorial(3)).to eq 6
end
it "computes the factorial of 4" do
expect(factorial(4)).to eq 24
end
it "computes the factorial of 5" do
expect(factorial(5)).to eq 120
end
it "computes the factorial of 6" do
expect(factorial(6)).to eq 720
end
it "computes the factorial of 7" do
expect(factorial(7)).to eq 5040
end
end
@jondeaton

This comment has been minimized.

Copy link

commented Jul 7, 2016

I like writing factorial as recursive:

def factorial(n): if n in [0,1]: return 1 else: return n * factorial(n -1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.