TheAlgorithms/JavaScript · error · TypeError

Input should be integer

Error message

Input should be integer

What it means

Thrown by fastFibonacci(N) as a TypeError when !Number.isInteger(N). The fast doubling algorithm relies on integer halving (Math.trunc(N/2)) and integer indexing, so non-integer, NaN, Infinity, or non-number inputs are rejected up front rather than producing garbage.

Source

Thrown at Dynamic-Programming/FastFibonacciNumber.js:20

 * @function fastFibonacci
 * @description fastFibonacci is same as fibonacci algorithm by calculating the sum of previous two fibonacci numbers but in O(log(n)).
 * @param {Integer} N - The input integer
 * @return {Integer} fibonacci of N.
 * @see [Fast_Fibonacci_Numbers](https://www.geeksforgeeks.org/fast-doubling-method-to-find-the-nth-fibonacci-number/)
 */

// recursive function that returns (F(n), F(n-1))
const fib = (N) => {
  if (N === 0) return [0, 1]
  const [a, b] = fib(Math.trunc(N / 2))
  const c = a * (b * 2 - a)
  const d = a * a + b * b
  return N % 2 ? [d, c + d] : [c, d]
}

const fastFibonacci = (N) => {
  if (!Number.isInteger(N)) {
    throw new TypeError('Input should be integer')
  }
  return fib(N)[0]
}

export { fastFibonacci }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Coerce to a non-negative integer first: Math.trunc(Number(input)), then validate isInteger.
  2. Validate at the boundary: if (!Number.isInteger(n)) reject before calling fastFibonacci.
  3. Strip units/strings from user input and parse with parseInt(value, 10).
  4. Reject Infinity/NaN explicitly since isInteger already excludes them but callers should fail fast.

Example fix

// before
const f = fastFibonacci(input) // throws if input is '10' or 5.5

// after
const n = Math.trunc(Number(input))
if (!Number.isInteger(n) || n < 0) throw new TypeError('N must be a non-negative integer')
const f = fastFibonacci(n)
Defensive patterns

Strategy: type-guard

Validate before calling

function safeFastFib(input) {
  const n = Math.trunc(Number(input))
  if (!Number.isInteger(n) || n < 0) {
    throw new TypeError('N must be a non-negative integer')
  }
  return fastFibonacci(n)
}

Type guard

const isNonNegInt = (n) => Number.isInteger(n) && n >= 0

Try / catch

try {
  return fastFibonacci(n)
} catch (e) {
  if (e instanceof TypeError && /integer/i.test(e.message)) {
    return fastFibonacci(Math.trunc(Number(n)))
  }
  throw e
}

Prevention

When it happens

Trigger: fastFibonacci(5.5); fastFibonacci('10') (string fails isInteger); fastFibonacci(Infinity); fastFibonacci(NaN); fastFibonacci(null) (null is not an integer).

Common situations: Input parsed from JSON/text as a float; division result fed in without rounding; BigInt or string leaking through from upstream parsing.

Related errors


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