find the nth hexagonal number in typescript

Here's a function in TypeScript to find the nth hexagonal number using the formula:

nth_hexagonal_number = n * (2n - 1)

index.ts
function findNthHexagonalNumber(n: number): number {
  let nthHexagonalNumber: number = 0;
  for(let i = 1; i <= n; i++) {
    nthHexagonalNumber = i * (2 * i - 1);
  }
  return nthHexagonalNumber;
}

// Example usage:
const nth = 5;
const result = findNthHexagonalNumber(nth);
console.log(`The ${nth}th hexagonal number is ${result}.`); // Output: The 5th hexagonal number is 61.
381 chars
13 lines

In this function, we start from i = 1 and go up to n, calculating the corresponding hexagonal number at each step using the formula i * (2i - 1). The final value of nthHexagonalNumber is returned.

You can test this implementation and modify the code as per your requirements.

gistlibby LogSnag