Instructions
Create a function factorial that calculates n! (n factorial).
factorial(0) = 1
factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
You can use recursion or iteration.
Hints:
- Base case: factorial(0) = 1
- Try using (1..n).reduce(1, :*)
- Or use recursion: n * factorial(n-1)
Your Code
def factorial(n) return 1 if n <= 1 (1..n).reduce(1, :*) end
RSpec.describe "factorial" do
it "returns 1 for 0" do
expect(factorial(0)).to eq(1)
end
it "returns 1 for 1" do
expect(factorial(1)).to eq(1)
end
it "calculates factorial of 5" do
expect(factorial(5)).to eq(120)
end
it "calculates factorial of 10" do
expect(factorial(10)).to eq(3628800)
end
end
Results
Click "Run Tests" to see results