TheAlgorithms/JavaScript · error · Error
Invalid Input
Error message
Invalid Input
What it means
Thrown by `nthPrime(n)` (Project Euler #7) when `n < 1`. The function returns the n-th prime via trial counting, so n must be a positive integer. The message is generic ('Invalid Input') so check the source line for the exact condition. Non-number inputs bypass the guard.
Source
Thrown at Project-Euler/Problem007.js:15
import { PrimeCheck } from '../Maths/PrimeCheck.js'
/**
* Find nth Prime Number
*
* P.S.(Project Euler - 007):
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
* What is the 10001st prime number?
*
* @param {Number} n
* @returns {Number} returns the nth prime number
*/
export const nthPrime = (n) => {
if (n < 1) {
throw new Error('Invalid Input')
}
let count = 0
let candidateValue = 1
while (count < n) {
candidateValue++
if (PrimeCheck(candidateValue)) {
count++
}
}
return candidateValue
}
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Validate `n >= 1` and is a finite integer upstream.
- Coerce with `Number(n)` so string/undefined inputs are caught.
- If 0 is semantically valid in your domain, decide on a fallback (e.g. return null) before calling.
Example fix
// before
nthPrime(req.query.n) // req.query.n could be '0' or undefined
// after
const n = Number(req.query.n)
if (!Number.isInteger(n) || n < 1) throw new RangeError('n must be a positive integer')
nthPrime(n) Defensive patterns
Strategy: validation
Validate before calling
const idx = Number(n)
if (!Number.isInteger(idx) || idx < 1) {
throw new RangeError('n must be a positive integer')
}
nthPrime(idx) Type guard
const isPositiveInt = (x) => typeof x === 'number' && Number.isInteger(x) && x >= 1
Prevention
- Coerce request params with Number() before forwarding.
- Be careful with 0-indexed vs 1-indexed caller logic.
- Pick a sensible default (e.g. 1) when the field is missing.
When it happens
Trigger: Call `nthPrime(0)`, `nthPrime(-3)`. `nthPrime(1)` is valid and returns 2.
Common situations: Defaulting a 'which prime' field to 0, off-by-one in 0-indexed vs 1-indexed logic, or a request parameter parsed as 0 when empty.
Related errors
- Invalid Input
- Invalid input
- Invalid Input
- No natural numbers exist below 1
- Fibonacci sequence limit can't be less than 1
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/8feb593345dd605a.
Report an issue: GitHub.