HomeSoftware EngineeringEasy methods to Remedy the Sum of Triangular Numbers in C

Easy methods to Remedy the Sum of Triangular Numbers in C


The problem

Your activity is to return the sum of Triangular Numbers up-to-and-including the nth Triangular Quantity.

Triangular Quantity: “any of the sequence of numbers (1, 3, 6, 10, 15, and many others.) obtained by continued summation of the pure numbers 1, 2, 3, 4, 5, and many others.”

[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 can’t be destructive so return 0 if a destructive quantity is given.

The answer in C

Choice 1:

int sumTriangularNumbers(int n) {
  if(n<=0) {
    return 0;
  }
  return n*(n+1)*(n+2)/6;
}

Choice 2:

int sumTriangularNumbers(int n) {
    int sum = 0, sumTot = 0;
    int i;
    for (i=1; i<= n; i++) {
        sum += i;
        sumTot += sum;
    }
    return sumTot;
}

Choice 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;
}

Take a look at circumstances to validate our answer

#embrace <criterion/criterion.h>

int sumTriangularNumbers(int);

Take a look at(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);
}
RELATED ARTICLES

Most Popular

Recent Comments