The challenge
Your task is to return the sum of Triangular Numbers up-to-and-including the nth
Triangular Number.
Triangular Number: “any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc.”
[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]
e.g. If 4
is given: 1 + 3 + 6 + 10 = 20
.
Triangular Numbers cannot be negative so return 0 if a negative number is given.
The solution in C
Option 1:
int sumTriangularNumbers(int n) {
if(n<=0) {
return 0;
}
return n*(n+1)*(n+2)/6;
}
Option 2:
int sumTriangularNumbers(int n) {
int sum = 0, sumTot = 0;
int i;
for (i=1; i<= n; i++) {
sum += i;
sumTot += sum;
}
return sumTot;
}
Option 3:
int sumTriangularNumbers(int n) {
int sum=0;
if(n<0)
return 0;
else {
for(int i=1;i<=n;++i)
for(int j =1;j<=i;++j)
sum+=j;
};
return sum;
}
Test cases to validate our solution
#include <criterion/criterion.h>
int sumTriangularNumbers(int);
Test(basicTests, should_pass_all_the_tests_provided) {
cr_assert_eq(sumTriangularNumbers(6), 56);
cr_assert_eq(sumTriangularNumbers(34), 7140);
cr_assert_eq(sumTriangularNumbers(-291), 0);
cr_assert_eq(sumTriangularNumbers(943), 140205240);
cr_assert_eq(sumTriangularNumbers(-971), 0);
}