Use a recursive method to calculate the sum of all integers from 1 to n.
An ArgumentError should be raised if the input is below 1.
def sum n raise ArgumentError('n must be greater than 0') if n < 1 n == 1 ? 1 : n + sum(n - 1) end
- def sum n
return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occurn + sum(n - 1)- raise ArgumentError('n must be greater than 0') if n < 1
- n == 1 ? 1 : n + sum(n - 1)
- end
describe "The function" do it "should sum up to 10 correctly" do Test.assert_equals sum(1), 1 Test.assert_equals sum(2), 3 Test.assert_equals sum(3), 6 Test.assert_equals sum(4), 10 Test.assert_equals sum(5), 15 Test.assert_equals sum(6), 21 Test.assert_equals sum(7), 28 Test.assert_equals sum(8), 36 Test.assert_equals sum(9), 45 Test.assert_equals sum(10), 55 end it "should sum up to larger numbers correctly too" do Test.assert_equals sum(20), 210 Test.assert_equals sum(30), 465 Test.assert_equals sum(40), 820 Test.assert_equals sum(50), 50 * (50 + 1) / 2 end it "should sum up to any number correctly" do 5.times do rand_int = Test.random_number Test.assert_equals sum(rand_int), rand_int * (rand_int + 1) / 2 end end it "should raise an argument error if n < 1" do Test.expect_error(ArgumentError) { sum(0) } Test.expect_error(ArgumentError) { sum(-100) } end end
- describe "The function" do
- it "should sum up to 10 correctly" do
- Test.assert_equals sum(1), 1
- Test.assert_equals sum(2), 3
- Test.assert_equals sum(3), 6
- Test.assert_equals sum(4), 10
- Test.assert_equals sum(5), 15
- Test.assert_equals sum(6), 21
- Test.assert_equals sum(7), 28
- Test.assert_equals sum(8), 36
- Test.assert_equals sum(9), 45
- Test.assert_equals sum(10), 55
- end
- it "should sum up to larger numbers correctly too" do
- Test.assert_equals sum(20), 210
- Test.assert_equals sum(30), 465
- Test.assert_equals sum(40), 820
- Test.assert_equals sum(50), 50 * (50 + 1) / 2
- end
- it "should sum up to any number correctly" do
- 5.times do
- rand_int = Test.random_number
- Test.assert_equals sum(rand_int), rand_int * (rand_int + 1) / 2
- end
- end
- it "should raise an argument error if n < 1" do
- Test.expect_error(ArgumentError) { sum(0) }
- Test.expect_error(ArgumentError) { sum(-100) }
- end
- end