TheAlgorithms/JavaScript · error · Error
Number must be greater than zero.
Error message
Number must be greater than zero.
What it means
The hexagonalNumber function computes the nth hexagonal number via the formula n*(2n-1). Hexagonal numbers are a figurate sequence defined only for n >= 1; zero and negative indices have no valid representation. The guard at line 18 rejects any number <= 0 before computing.
Source
Thrown at Maths/HexagonalNumber.js:18
/*
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
* Hexagonal Number: https://en.wikipedia.org/wiki/Hexagonal_number
* The nth hexagonal number hn is the number of distinct dots in a pattern of dots
* consisting of the outlines of regular hexagons with sides up to n dots, when the
* hexagons are overlaid so that they share one vertex.
*/
/**
* @function hexagonalNumber
* @description -> returns nth hexagonal number
* @param {Integer} number
* @returns {Integer} nth hexagonal number
*/
export const hexagonalNumber = (number) => {
if (number <= 0) {
throw new Error('Number must be greater than zero.')
}
return number * (2 * number - 1)
}
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a positive integer (n >= 1) to hexagonalNumber.
- If iterating from a 0-based index, add 1 before calling: hexagonalNumber(i + 1).
- Validate user input is >= 1 before invoking the function.
Example fix
// before
for (let i = 0; i < 5; i++) {
hexagonalNumber(i) // throws when i === 0
}
// after
for (let i = 1; i <= 5; i++) {
hexagonalNumber(i)
} Defensive patterns
Strategy: validation
Validate before calling
if (!Number.isInteger(number) || number <= 0) {
throw new RangeError('number must be a positive integer')
}
const result = hexagonalNumber(number) Type guard
const isPositiveInteger = (n) => typeof n === 'number' && Number.isInteger(n) && n > 0
Prevention
- Use 1-based indexing for figurate-number sequence functions.
- Validate positive integers before calling number-theory or figurate-number functions.
- Never pass raw 0-based loop indices to functions expecting 1-based positions.
When it happens
Trigger: Calling hexagonalNumber(0), hexagonalNumber(-1), or passing any non-positive value. A 0-based loop index fed directly into the function triggers it on the first iteration.
Common situations: Off-by-one loop starting at 0 instead of 1, using a 0-indexed array position as the figurate number argument, zero-defaulted variables, or user input parsed as 0.
Related errors
- Input data must be numbers
- Expected a valid real number
- Number must be greater than zero.
- Number must be greater than zero.
- Index cannot be Negative
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/0a9b3f198506e88a.
Report an issue: GitHub.