{"record":{"id":"46c3af7f6ab75f3c","repo":"TheAlgorithms/Java","slug":"input-number-cannot-be-negative","errorCode":null,"errorMessage":"Input number cannot be negative","messagePattern":"Input number cannot be negative","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/Factorial.java","lineNumber":11,"sourceCode":"package com.thealgorithms.maths;\n\nimport java.math.BigInteger;\n\npublic final class Factorial {\n    private Factorial() {\n    }\n\n    public static BigInteger factorial(int n) {\n        if (n < 0) {\n            throw new IllegalArgumentException(\"Input number cannot be negative\");\n        }\n        BigInteger result = BigInteger.ONE;\n        for (int i = 1; i <= n; i++) {\n            result = result.multiply(BigInteger.valueOf(i));\n        }\n        return result;\n    }\n}\n","sourceCodeStart":1,"sourceCodeEnd":20,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/Factorial.java#L1-L20","documentation":"Thrown by Factorial.factorial when n < 0. Factorial is defined for non-negative integers; the iterative loop `for (i = 1; i <= n; i++)` would not execute for negative n and would silently return 1 (wrong), so the library rejects negatives explicitly to avoid a silently incorrect result.","triggerScenarios":"Calling factorial(-1) or any negative n. Common when n is derived from a subtraction or parsed from unvalidated input.","commonSituations":"n computed as a - b that can go negative; user input not bounded; loop boundaries that include 0 or below; off-by-one in decrementing logic.","solutions":["Pass a non-negative integer n (>= 0); factorial(0) correctly returns 1.","Guard at the caller: if (n < 0) reject or clamp to 0.","Validate parsed input before invoking."],"exampleFix":"// before\nBigInteger f = Factorial.factorial(count - 1); // count == 0 => -1\n\n// after\nBigInteger f = Factorial.factorial(Math.max(0, count - 1));","handlingStrategy":"validation","validationCode":"if (n < 0) {\n    throw new IllegalArgumentException(\"factorial requires n >= 0\");\n}\nFactorial.factorial(n);","typeGuard":"static boolean isNonNegative(int n) { return n >= 0; }","tryCatchPattern":null,"preventionTips":["Guard factorial(a - b) with Math.max(0, a - b).","Validate parsed integers before calling.","Remember factorial(0) is valid and returns 1."],"tags":["validation","number-theory","precondition"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}