Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the sum of all numbers in the nth row of an increasing triangle using JavaScript
For the purpose of this problem, an increasing triangle is a structure where numbers are arranged in rows, with each row containing one more number than the previous row, and all numbers are consecutive starting from 1.
Understanding the Triangle Structure
The increasing triangle looks like this:
1 2 3 4 5 6 7 8 9 10
Each row n contains n consecutive numbers. Row 1 has 1 number, row 2 has 2 numbers, row 3 has 3 numbers, and so on.
Problem Statement
We need to write a JavaScript function that takes a number n and returns the sum of all numbers in the nth row of this increasing triangle.
Method 1: Using Array Generation
This approach builds the triangle structure and calculates the sum:
const rowSum = (num = 1) => {
const arr = [];
const fillArray = () => {
let currentNum = 0;
for (let i = 1; i <= num; i++) {
const tempArr = [];
for (let j = 0; j < i; j++) {
currentNum++;
tempArr.push(currentNum);
}
arr.push(tempArr);
}
};
fillArray();
return arr[num - 1].reduce((a, b) => a + b, 0);
};
console.log(rowSum(4)); // Sum of row 4: 7+8+9+10
console.log(rowSum(3)); // Sum of row 3: 4+5+6
34 15
Method 2: Mathematical Formula (Optimized)
Instead of generating arrays, we can use a mathematical approach. The first number in row n starts at position (n-1)*n/2 + 1:
const rowSumOptimized = (n) => {
// First number in row n
const firstNum = ((n - 1) * n) / 2 + 1;
// Sum of n consecutive numbers starting from firstNum
// Formula: n * firstNum + n*(n-1)/2
return n * firstNum + (n * (n - 1)) / 2;
};
console.log(rowSumOptimized(4)); // Row 4: 7+8+9+10
console.log(rowSumOptimized(3)); // Row 3: 4+5+6
console.log(rowSumOptimized(15)); // Row 15
34 15 1695
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Array Generation | O(n²) | O(n²) | Small values of n |
| Mathematical Formula | O(1) | O(1) | Large values of n |
How the Formula Works
For row n:
- Total numbers before row n: (n-1) × n ÷ 2
- First number in row n: ((n-1) × n ÷ 2) + 1
- Row n contains n consecutive numbers
- Sum = n × first_number + sum of first (n-1) natural numbers
Conclusion
The mathematical formula provides an O(1) solution for finding the sum of any row in an increasing triangle. For large values of n, this approach is significantly more efficient than generating the entire triangle structure.
