{"record":{"id":"8e14186872c33cad","repo":"TheAlgorithms/Java","slug":"number-must-be-non-negative-given","errorCode":null,"errorMessage":"Number must be non-negative. Given: ","messagePattern":"Number must be non-negative\\. Given: ","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/KaprekarNumbers.java","lineNumber":81,"sourceCode":"     * <p>\n     * The algorithm works as follows:\n     * <ol>\n     * <li>Square the number</li>\n     * <li>Split the squared number into two parts: left and right</li>\n     * <li>The right part has the same number of digits as the original number</li>\n     * <li>Add the left and right parts</li>\n     * <li>If the sum equals the original number, it's a Kaprekar number</li>\n     * </ol>\n     * <p>\n     * Special handling is required for numbers whose squares contain zeros.\n     *\n     * @param num the number to check\n     * @return true if the number is a Kaprekar number, false otherwise\n     * @throws IllegalArgumentException if num is negative\n     */\n    public static boolean isKaprekarNumber(long num) {\n        if (num < 0) {\n            throw new IllegalArgumentException(\"Number must be non-negative. Given: \" + num);\n        }\n\n        if (num == 0 || num == 1) {\n            return true;\n        }\n\n        String number = Long.toString(num);\n        BigInteger originalNumber = BigInteger.valueOf(num);\n        BigInteger numberSquared = originalNumber.multiply(originalNumber);\n        String squaredStr = numberSquared.toString();\n\n        // Special case: if the squared number has the same length as the original\n        if (number.length() == squaredStr.length()) {\n            return number.equals(squaredStr);\n        }\n\n        // Calculate the split position\n        int splitPos = squaredStr.length() - number.length();","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java#L63-L99","documentation":"Thrown by isKaprekarNumber(long num) when the input is negative. A Kaprekar number is one whose square can be split into left and right parts that sum back to the original (e.g., 45 squared is 2025, and 20+25=45). The method requires non-negative input because the algorithm splits the squared representation, and negative numbers have no meaningful split semantics.","triggerScenarios":"Calling KaprekarNumbers.isKaprekarNumber(-1) or passing any negative long value. Also triggered by downstream code that forwards unparsed user input or database sentinel values like -1.","commonSituations":"Accepting user input from a text field or API parameter that was not range-validated. Processing data files where missing values are encoded as -1. Subtracting two values where the result may go negative before passing to isKaprekarNumber.","solutions":["Validate that the input is >= 0 before calling isKaprekarNumber","Filter or reject negative inputs at the data-ingestion boundary (API handler, file parser) rather than at the algorithm call site","If the absolute value is acceptable for your use case, pass Math.abs(num) instead"],"exampleFix":"// before\nboolean result = KaprekarNumbers.isKaprekarNumber(userInput);\n\n// after\nif (userInput < 0) {\n    throw new IllegalArgumentException(\"Input must be non-negative: \" + userInput);\n}\nboolean result = KaprekarNumbers.isKaprekarNumber(userInput);","handlingStrategy":"validation","validationCode":"if (num < 0) {\n    throw new IllegalArgumentException(\"Input must be non-negative: \" + num);\n}\nboolean result = KaprekarNumbers.isKaprekarNumber(num);","typeGuard":"static boolean isValidKaprekarInput(long num) {\n    return num >= 0;\n}","tryCatchPattern":"try {\n    boolean result = KaprekarNumbers.isKaprekarNumber(num);\n} catch (IllegalArgumentException e) {\n    // handle invalid input — log and skip or default to false\n    logger.warn(\"Invalid Kaprekar input: {}\", num);\n}","preventionTips":["Validate all numeric inputs at the API or data-ingestion boundary before passing to algorithm methods","Use sentinel values like -1 for missing data only if you filter them before algorithm calls","Write unit tests that include boundary cases: 0, 1, and negative values"],"tags":["math","validation","illegal-argument","number-theory"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}