Last active
July 7, 2016 22:08
-
-
Save nbkhope/03c0216f2a3784f75330cadfe3ab0826 to your computer and use it in GitHub Desktop.
Introduction to RSpec and Test-Driven Development using Factorial
This file contains 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
# 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 |
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like writing factorial as recursive:
def factorial(n): if n in [0,1]: return 1 else: return n * factorial(n -1)