Skip to content

Commit d6be3a4

Browse files
algorithm: Hexagonal number (TheAlgorithms#1265)
1 parent 71d3d44 commit d6be3a4

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Maths/HexagonalNumber.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
3+
* Hexagonal Number: https://en.wikipedia.org/wiki/Hexagonal_number
4+
* The nth hexagonal number hn is the number of distinct dots in a pattern of dots
5+
* consisting of the outlines of regular hexagons with sides up to n dots, when the
6+
* hexagons are overlaid so that they share one vertex.
7+
*/
8+
9+
/**
10+
* @function hexagonalNumber
11+
* @description -> returns nth hexagonal number
12+
* @param {Integer} number
13+
* @returns {Integer} nth hexagonal number
14+
*/
15+
16+
export const hexagonalNumber = (number) => {
17+
if (number <= 0) {
18+
throw new Error('Number must be greater than zero.')
19+
}
20+
return number * (2 * number - 1)
21+
}

Maths/test/HexagonalNumber.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { hexagonalNumber } from '../HexagonalNumber'
2+
3+
const expectedValuesArray = [1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435, 496, 561, 630, 703, 780, 861, 946]
4+
5+
describe('Testing hexagonalNumber', () => {
6+
for (let i = 1; i <= 22; i++) {
7+
it('Testing for number = ' + i + ', should return ' + expectedValuesArray[i], () => {
8+
expect(hexagonalNumber(i)).toBe(expectedValuesArray[i - 1])
9+
})
10+
}
11+
12+
it('should throw error when supplied negative numbers', () => {
13+
expect(() => { hexagonalNumber(-1) }).toThrow(Error)
14+
})
15+
16+
it('should throw error when supplied zero', () => {
17+
expect(() => { hexagonalNumber(0) }).toThrow(Error)
18+
})
19+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy