Skip to content

Commit 23ec55c

Browse files
committed
feat: added hexagonal numbers 📏✏️
1 parent e693ba1 commit 23ec55c

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Maths/Series/HexagonalNumbers.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function HexagonalNumbers
3+
* @description To generate the requested number of hexagonal numbers
4+
* @summary A hexagonal number, hₙ, is a figurate number which represents the number
5+
* of distinct dots in a pattern of dots consisting of the outlines of regular
6+
* hexagons with sides upto 'n' dots, when the hexagons are overlaid so that they share a common vertex
7+
*
8+
* The nth hexagonal number, hₙ, is calculated by the formula:
9+
* hₙ = n * (2n - 1)
10+
* @see [Wikipedia](https://en.wikipedia.org/wiki/Hexagonal_number)
11+
* @see [OEIS](https://oeis.org/A000384)
12+
* @param {number} n - The number of Hexagonal numbers to generate
13+
* @returns {number[]} - An array containing first 'n' hexagonal numbers
14+
* @example HexagonalNumbers(10) = [ 1, 6, 15, 28, 45, 66, 91, 120, 153, 190 ]
15+
* @example HexagonalNumbers(15) = [ 1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435 ]
16+
*/
17+
export const HexagonalNumbers = (n: number): number[] => {
18+
if (isNaN(n)) throw new Error('The input needs to be a number')
19+
if (!Number.isInteger(n) || n < 0) throw new Error('The input needs to be a non-negative integer')
20+
const hexagonalNumbers = []
21+
22+
for (let i = 1; i <= n; i++) {
23+
hexagonalNumbers.push(i * (2 * i - 1))
24+
}
25+
26+
return hexagonalNumbers
27+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { HexagonalNumbers } from "../HexagonalNumbers";
2+
3+
describe("HexagonalNumbers", () => {
4+
it("should return the first 10 hexagonal numbers", () => {
5+
expect(HexagonalNumbers(10)).toStrictEqual([1, 6, 15, 28, 45, 66, 91, 120, 153, 190]);
6+
})
7+
8+
it("should return the first 5 hexagonal numbers", () => {
9+
expect(HexagonalNumbers(5)).toStrictEqual([1, 6, 15, 28, 45])
10+
})
11+
12+
it("should return zero hexagonal numbers", () => {
13+
expect(HexagonalNumbers(0)).toStrictEqual([])
14+
})
15+
})

0 commit comments

Comments
 (0)