Finding the sum of all numbers in the nth row of an increasing triangle using JavaScript


Increasing Triangle

For the purpose of this problem, suppose an increasing triangle to be like this −

   1
  2 3
 4 5 6
7 8 9 10

Problem

We are required to write a JavaScript function that takes in a number n and returns the sum of numbers present in the nth row of increasing triangle.

Example

Following is the code −

 Live Demo

const num = 15;
const rowSum = (num = 1) => {
   const arr = [];
   const fillarray = () => {
      let num = 0;
      for(let i = 1; i <= 10000; i++){
         const tempArr = [];
         for(let j = 0; j < i; j++){
            num++;
            tempArr.push(num)
         };
         arr.push(tempArr);
      };
   };
   fillarray()
   return arr[num-1].reduce((a, b)=>a + b, 0);
};
console.log(rowSum(num));

Output

1695

Updated on: 19-Apr-2021

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements