TheAlgorithms/JavaScript · error · Error

Invalid Input

Error message

Invalid Input

What it means

Thrown by `problem21(n)` (Project Euler #21, amicable numbers) when `n < 2`. The search loop starts at `a = 2`, so an upper bound below 2 yields nothing. The message is generic. Non-number inputs bypass the guard because comparisons with undefined/NaN return false.

Source

Thrown at Project-Euler/Problem021.js:19

import { aliquotSum } from '../Maths/AliquotSum.js'

/**
 * Problem 21 - Amicable numbers
 *
 * @see {@link https://projecteuler.net/problem=21}
 *
 * Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
 * If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
 * For example, the proper divisors of 220 are 1,2,4,5,10,11,20,22,44,55 and 110; therefore d(220) = 284.
 * The proper divisors of 284 are 1,2,4,71 and 142; so d(284) = 220.
 * Evaluate the sum of all amicable numbers under 10000
 *
 * @author PraneethJain
 */

function problem21(n) {
  if (n < 2) {
    throw new Error('Invalid Input')
  }

  let result = 0
  for (let a = 2; a < n; ++a) {
    const b = aliquotSum(a) // Sum of all proper divisors of a
    // Check if b > a to ensure each pair isn't counted twice, and check if sum of proper divisors of b is equal to a
    if (b > a && aliquotSum(b) === a) {
      result += a + b
    }
  }
  return result
}

export { problem21 }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Validate `n >= 2` and is a finite integer upstream.
  2. Coerce with `Number(n)` so non-numbers do not slip past the guard.
  3. Pick a sensible default (e.g. 10000) when the field is missing.

Example fix

// before
problem21(upperBound) // upperBound could be 1

// after
const n = Number(upperBound)
if (!Number.isInteger(n) || n < 2) throw new RangeError('n must be an integer >= 2')
problem21(n)
Defensive patterns

Strategy: validation

Validate before calling

const n = Number(bound)
if (!Number.isInteger(n) || n < 2) {
  throw new RangeError('n must be an integer >= 2')
}
problem21(n)

Type guard

const isIntAtLeast2 = (x) => typeof x === 'number' && Number.isInteger(x) && x >= 2

Prevention

When it happens

Trigger: Call `problem21(0)`, `problem21(1)`, `problem21(-5)`. `n = 2` passes but finds no amicable pairs below 2.

Common situations: Defaulting an 'upper limit' field to 0 or 1, off-by-one from inclusive vs exclusive interpretation, or a request param parsed as 1.

Related errors


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