{"record":{"id":"61a9a8d611fd125b","repo":"TheAlgorithms/C-Sharp","slug":"the-value-listofas-first-x-x-0-for-some-a-i-is-smaller-than","errorCode":null,"errorMessage":"The value {listOfAs.First(x => x < 0)} for some a_i is smaller than 0.","messagePattern":"The value (.+?) for some a_i is smaller than 0\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/ModularArithmetic/ChineseRemainderTheorem.cs","lineNumber":134,"sourceCode":"    /// </summary>\n    /// <param name=\"listOfAs\">An ordered list of a_0, a_1, ..., a_k.</param>\n    /// <param name=\"listOfNs\">An ordered list of n_0, n_1, ..., n_k.</param>\n    /// <exception cref=\"ArgumentException\">If any of the requirements is not fulfilled.</exception>\n    private static void CheckRequirements(List<long> listOfAs, List<long> listOfNs)\n    {\n        if (listOfAs == null || listOfNs == null || listOfAs.Count != listOfNs.Count)\n        {\n            throw new ArgumentException(\"The parameters 'listOfAs' and 'listOfNs' must not be null and have to be of equal length!\");\n        }\n\n        if (listOfNs.Any(x => x <= 1))\n        {\n            throw new ArgumentException($\"The value {listOfNs.First(x => x <= 1)} for some n_i is smaller than or equal to 1.\");\n        }\n\n        if (listOfAs.Any(x => x < 0))\n        {\n            throw new ArgumentException($\"The value {listOfAs.First(x => x < 0)} for some a_i is smaller than 0.\");\n        }\n\n        // Check if all pairs of (n_i, n_j) are coprime:\n        for (var i = 0; i < listOfNs.Count; i++)\n        {\n            for (var j = i + 1; j < listOfNs.Count; j++)\n            {\n                long gcd;\n                if ((gcd = ExtendedEuclideanAlgorithm.Compute(listOfNs[i], listOfNs[j]).Gcd) != 1L)\n                {\n                    throw new ArgumentException($\"The GCD of n_{i} = {listOfNs[i]} and n_{j} = {listOfNs[j]} equals {gcd} and thus these values aren't coprime.\");\n                }\n            }\n        }\n    }\n\n    /// <summary>\n    /// Checks the requirements for the algorithm and throws an ArgumentException if they are not being met.","sourceCodeStart":116,"sourceCodeEnd":152,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/ModularArithmetic/ChineseRemainderTheorem.cs#L116-L152","documentation":"The CRT construction assumes each remainder a_i is a non-negative residue. CheckRequirements throws ArgumentException identifying the first negative a_i, since a negative remainder falls outside the canonical residue range for its modulus.","triggerScenarios":"Calling Compute where any entry of listOfAs is negative, e.g. remainders taken directly from signed arithmetic like -3 mod 5 instead of normalizing to 2.","commonSituations":"Users entering remainders as negative numbers (\"x ≡ -1 (mod 5)\"); computing remainders in C# where % can return negative values for negative operands.","solutions":["Normalize each remainder into [0, n_i) before calling Compute: a = ((a % n) + n) % n.","Validate listOfAs for negatives in the caller and reject or normalize them with a clear message.","Fix the upstream remainder computation to use a proper mathematical mod operation."],"exampleFix":"// before\nChineseRemainderTheorem.Compute(new List<long> { -1 }, new List<long> { 5 }); // throws\n\n// after\nvar normalized = listOfAs.Zip(listOfNs, (a, n) => ((a % n) + n) % n).ToList();\nChineseRemainderTheorem.Compute(normalized, listOfNs);","handlingStrategy":"validation","validationCode":"var normalized = listOfAs.Zip(listOfNs, (a, n) => ((a % n) + n) % n).ToList();\nChineseRemainderTheorem.Compute(normalized, listOfNs);","typeGuard":"static bool HasNonNegativeRemainders(List<long> as_) => as_ != null && as_.All(a => a >= 0);","tryCatchPattern":"try\n{\n    var result = ChineseRemainderTheorem.Compute(listOfAs, listOfNs);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"some a_i is smaller than 0\"))\n{\n    logger.LogError(\"Negative remainder in CRT input: {Msg}\", ex.Message);\n    throw;\n}","preventionTips":["Always normalize remainders with ((a % n) + n) % n, since C# % can return negatives.","When accepting user input like \"x ≡ -1 (mod 5)\", normalize before passing through.","Add a property-based test that random integers are normalized into [0, n)."],"tags":["math","modular-arithmetic","value-out-of-range","csharp"],"backgroundTag":"value-out-of-range","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}