TheAlgorithms/JavaScript · error · Error

Invalid Input

Error message

Invalid Input

What it means

Thrown by `problem44(k)` (Project Euler #44, pentagonal numbers) when `k < 1`. The function immediately increments `k` and loops, so a starting k below 1 has no meaning. The message is generic. Non-number inputs bypass the guard.

Source

Thrown at Project-Euler/Problem044.js:16

/**
 * Problem 44 - Pentagon numbers
 *
 * @see {@link https://projecteuler.net/problem=44}
 *
 * Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:
 * 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
 * It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
 * Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
 *
 * @author ddaniel27
 */

function problem44(k) {
  if (k < 1) {
    throw new Error('Invalid Input')
  }

  while (true) {
    k++
    const n = (k * (3 * k - 1)) / 2 // calculate Pk

    for (let j = k - 1; j > 0; j--) {
      const m = (j * (3 * j - 1)) / 2 // calculate all Pj < Pk
      if (isPentagonal(n - m) && isPentagonal(n + m)) {
        // Check sum and difference
        return n - m // return D
      }
    }
  }
}

/**
 * Function to check if a number is pentagonal or not

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Validate `k >= 1` and is a finite integer upstream.
  2. Coerce with `Number(k)` so string/undefined inputs are caught.
  3. Note the function loops indefinitely until a pair is found - consider a timeout wrapper for large inputs.

Example fix

// before
problem44(startIndex) // could be 0

// after
const k = Number(startIndex)
if (!Number.isInteger(k) || k < 1) throw new RangeError('k must be an integer >= 1')
problem44(k)
Defensive patterns

Strategy: validation

Validate before calling

const k = Number(startIndex)
if (!Number.isInteger(k) || k < 1) {
  throw new RangeError('k must be an integer >= 1')
}
problem44(k)

Type guard

const isPositiveInt = (x) => typeof x === 'number' && Number.isInteger(x) && x >= 1

Prevention

When it happens

Trigger: Call `problem44(0)`, `problem44(-2)`. `k = 1` passes and starts the search.

Common situations: Defaulting a 'starting index' field to 0, off-by-one from 0-indexed vs 1-indexed caller logic, or a param parsed as 0.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/d3330c9392bb730d. Report an issue: GitHub.