find the nth triangular number in typescript

Here's a TypeScript function to find the nth triangular number using a simple loop:

index.ts
function getTriangularNumber(n: number): number {
  let sum = 0;

  for (let i = 1; i <= n; i++) {
    sum += i;
  }

  return sum;
}
134 chars
10 lines

This function takes a number n as input and returns the nth triangular number. The loop iterates from 1 to n, adding each number to a running sum. At the end of the loop, the sum is returned as the nth triangular number.

For example, calling getTriangularNumber(5) would return 15, as the 5th triangular number is 1 + 2 + 3 + 4 + 5 = 15.

gistlibby LogSnag