find the nth octagonal number in typescript

Here's how to find the nth octagonal number in TypeScript:

index.ts
function getOctagonalNumber(n: number): number {
  return n * (3 * n - 2);
}
77 chars
4 lines

The formula for the nth octagonal number is 3n^2 - 2n, which can be simplified to n(3n - 2). This code uses the formula to calculate the nth octagonal number and returns the result.

Here's how to use the function:

index.ts
const n = 5;
const octagonalNumber = getOctagonalNumber(n);

console.log(`The ${n}th octagonal number is ${octagonalNumber}`);
127 chars
5 lines

This code sets n to 5 and calls the getOctagonalNumber function to calculate the 5th octagonal number. The result is stored in octagonalNumber and printed to the console.

Output:

index.ts
The 5th octagonal number is 145
32 chars
2 lines

gistlibby LogSnag