TheAlgorithms/JavaScript · error · TypeError
Input must be Numbers
Error message
Input must be Numbers
What it means
The ModRing arithmetic methods (add, etc.) call isInputValid which requires both operands to be number primitives. This check fires after the modulus-initialization check. Note that BigInt values fail this check because typeof 3n is 'bigint', not 'number'.
Source
Thrown at Maths/ModularArithmetic.js:20
/**
* https://brilliant.org/wiki/modular-arithmetic/
* @param {Number} arg1 first argument
* @param {Number} arg2 second argument
* @returns {Number}
*/
export class ModRing {
constructor(MOD) {
this.MOD = MOD
}
isInputValid = (arg1, arg2) => {
if (!this.MOD) {
throw new Error('Modulus must be initialized in the object constructor')
}
if (typeof arg1 !== 'number' || typeof arg2 !== 'number') {
throw new TypeError('Input must be Numbers')
}
}
/**
* Modulus is Distributive property,
* As a result, we separate it into numbers in order to keep it within MOD's range
*/
add = (arg1, arg2) => {
this.isInputValid(arg1, arg2)
return ((arg1 % this.MOD) + (arg2 % this.MOD)) % this.MOD
}
subtract = (arg1, arg2) => {
this.isInputValid(arg1, arg2)
// An extra MOD is added to check negative results
return ((arg1 % this.MOD) - (arg2 % this.MOD) + this.MOD) % this.MOD
}
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass number primitives (not strings or BigInts) to ModRing methods.
- Convert string input with Number() before calling.
- If working with large numbers, avoid BigInt; use plain numbers or a BigInt-compatible library instead.
Example fix
// before ring.add(a, b) // a or b might be strings // after ring.add(Number(a), Number(b))
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof arg1 !== 'number' || typeof arg2 !== 'number') {
throw new TypeError('Both arguments must be numbers')
}
ring.add(arg1, arg2) Type guard
const areNumbers = (a, b) => typeof a === 'number' && typeof b === 'number'
Prevention
- Avoid using BigInt with ModRing; convert to plain numbers or use a BigInt-compatible library.
- Convert string operands to Number() before calling arithmetic methods.
- Default optional parameters to 0 rather than leaving them undefined.
When it happens
Trigger: Calling ring.add("3", 5), ring.add(3n, 5) (BigInt), ring.add(null, 5), or passing any non-number type as either argument.
Common situations: String numbers from user input, BigInt used for large modular arithmetic, or null/undefined from optional parameters that were not defaulted.
Related errors
- Input data must be numbers
- Invalid Input
- Argument must be an Array
- Argument is not a number.
- The ${paramName} should be type Number
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/13d0f25464f69652.
Report an issue: GitHub.