find the nth octagonal number in javascript

An octagonal number is a figurate number that represents the number of dots in an octagon. The nth octagonal number can be calculated using the following formula:

n(3n-2)

We can write a JavaScript function that takes a value of n as input and returns the nth octagonal number using the formula mentioned above.

index.tsx
function getNthOctagonalNumber(n) {
  if (n === 0) return 0;
  return n * (3 * n - 2);
}
89 chars
5 lines

This function first checks if the input value of n is 0, in which case it returns 0 as the 0th octagonal number is defined to be 0. Otherwise, it applies the formula n(3n-2) to find the nth octagonal number and returns the result.

For example, if you want to find the 5th octagonal number, you can call the function like this:

index.tsx
const fifthOctagonalNumber = getNthOctagonalNumber(5);
console.log(fifthOctagonalNumber); // Output: 79
104 chars
3 lines

The output will be 79 as the 5th octagonal number is 79.

gistlibby LogSnag