TheAlgorithms/JavaScript · error · Error

Fibonacci sequence limit can't be less than 1

Error message

Fibonacci sequence limit can't be less than 1

What it means

Thrown by `EvenFibonacci(limit)` (Project Euler #2) when `limit < 1`. The closed-form formula uses `Math.log(limit * SQ5)` which is undefined or negative for limits below 1, so the guard rejects them. Non-number inputs (undefined, NaN) bypass it because comparisons with undefined/NaN return false.

Source

Thrown at Project-Euler/Problem002.js:9

// https://projecteuler.net/problem=2
const SQ5 = 5 ** 0.5 // Square root of 5
const PHI = (1 + SQ5) / 2 // definition of PHI

// theoretically it should take O(1) constant amount of time as long
// arithmetic calculations are considered to be in constant amount of time
export const EvenFibonacci = (limit) => {
  if (limit < 1)
    throw new Error("Fibonacci sequence limit can't be less than 1")

  const highestIndex = Math.floor(Math.log(limit * SQ5) / Math.log(PHI))
  const n = Math.floor(highestIndex / 3)
  return Math.floor(
    ((PHI ** (3 * n + 3) - 1) / (PHI ** 3 - 1) -
      ((1 - PHI) ** (3 * n + 3) - 1) / ((1 - PHI) ** 3 - 1)) /
      SQ5
  )
}

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Validate `limit >= 1` and is a finite number upstream.
  2. Coerce non-number inputs with `Number(limit)` before validation.
  3. Treat `limit < 1` as 'empty sum = 0' in the caller if that fits your domain.

Example fix

// before
EvenFibonacci(config.upperBound) // could be 0

// after
const limit = Number(config.upperBound)
if (!Number.isFinite(limit) || limit < 1) throw new RangeError('limit must be >= 1')
EvenFibonacci(limit)
Defensive patterns

Strategy: validation

Validate before calling

const l = Number(limit)
if (!Number.isFinite(l) || l < 1) {
  throw new RangeError('limit must be a finite number >= 1')
}
EvenFibonacci(l)

Prevention

When it happens

Trigger: Call `EvenFibonacci(0)`, `EvenFibonacci(-10)`. `limit = 1` passes but yields 0 because the highest even Fibonacci below 1 is none.

Common situations: Defaulting a config field to 0 when unset, off-by-one from inclusive/exclusive boundary confusion, or a UI spinner that allows 0.

Related errors


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