{"record":{"id":"0fb5f63c9fb58f48","repo":"TheAlgorithms/C-Sharp","slug":"cannot-calculate-the-square-root-of-a-negative-number","errorCode":null,"errorMessage":"Cannot calculate the square root of a negative number.","messagePattern":"Cannot calculate the square root of a negative number\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/NewtonSquareRoot.cs","lineNumber":9,"sourceCode":"﻿namespace Algorithms;\n\npublic static class NewtonSquareRoot\n{\n    public static BigInteger Calculate(BigInteger number)\n    {\n        if (number < 0)\n        {\n            throw new ArgumentException(\"Cannot calculate the square root of a negative number.\");\n        }\n\n        if (number == 0)\n        {\n            return BigInteger.Zero;\n        }\n\n        var bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(number, 2)));\n        BigInteger root = BigInteger.One << (bitLength / 2);\n\n        while (!IsSquareRoot(number, root))\n        {\n            root += number / root;\n            root /= 2;\n        }\n\n        return root;\n    }","sourceCodeStart":1,"sourceCodeEnd":27,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/NewtonSquareRoot.cs#L1-L27","documentation":"NewtonSquareRoot.Calculate throws when given a negative BigInteger, since a real square root does not exist for negative numbers and the Newton iteration only converges on non-negative inputs. This is a domain guard at the top of the public Calculate method.","triggerScenarios":"Calling NewtonSquareRoot.Calculate(x) with x < 0, often from distance formulas, discriminants (b²-4ac < 0), or subtraction results that unexpectedly went negative.","commonSituations":"Euclidean distance code with floating-point/BigInteger rounding causing negative squared distances; quadratic-formula implementations hitting negative discriminants; upstream sign errors propagating into the sqrt call.","solutions":["Check number >= 0 before calling Calculate and handle negatives in your domain logic (e.g. return complex or throw a domain-specific error).","Fix the upstream computation that produces the negative value (e.g. clamp squared distances to zero).","If negatives are expected, branch on the discriminant instead of calling sqrt unconditionally."],"exampleFix":"// before\nvar root = NewtonSquareRoot.Calculate(discriminant);\n// after\nif (discriminant < 0)\n    throw new InvalidOperationException(\"No real solution: negative discriminant.\");\nvar root = NewtonSquareRoot.Calculate(discriminant);","handlingStrategy":"validation","validationCode":"if (number < 0) throw new InvalidOperationException(\"cannot take square root of a negative value\");","typeGuard":"static bool IsNonNegative(System.Numerics.BigInteger x) => x.Sign >= 0;","tryCatchPattern":"try { root = NewtonSquareRoot.Calculate(x); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"negative\")) { /* handle complex/no-real-root case */ }","preventionTips":["Clamp squared distances and similar quantities to >= 0.","Branch on discriminants before taking square roots.","Assert non-negativity at computation boundaries."],"tags":["csharp","math","sqrt","biginteger"],"backgroundTag":"argument-out-of-range","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}