TheAlgorithms/C-Sharp · error · ArgumentException

Cannot calculate the square root of a negative number.

Error message

Cannot calculate the square root of a negative number.

What it means

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.

Solutions

  1. Check number >= 0 before calling Calculate and handle negatives in your domain logic (e.g. return complex or throw a domain-specific error).
  2. Fix the upstream computation that produces the negative value (e.g. clamp squared distances to zero).
  3. If negatives are expected, branch on the discriminant instead of calling sqrt unconditionally.

Example fix

// before
var root = NewtonSquareRoot.Calculate(discriminant);
// after
if (discriminant < 0)
    throw new InvalidOperationException("No real solution: negative discriminant.");
var root = NewtonSquareRoot.Calculate(discriminant);
Defensive patterns

Strategy: validation

Validate before calling

if (number < 0) throw new InvalidOperationException("cannot take square root of a negative value");

Type guard

static bool IsNonNegative(System.Numerics.BigInteger x) => x.Sign >= 0;

Try / catch

try { root = NewtonSquareRoot.Calculate(x); }
catch (ArgumentException ex) when (ex.Message.Contains("negative")) { /* handle complex/no-real-root case */ }

Prevention

When it happens

Trigger: Calling NewtonSquareRoot.Calculate(x) with x < 0, often from distance formulas, discriminants (b²-4ac < 0), or subtraction results that unexpectedly went negative.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/0fb5f63c9fb58f48. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/NewtonSquareRoot.cs:9

namespace Algorithms;

public static class NewtonSquareRoot
{
    public static BigInteger Calculate(BigInteger number)
    {
        if (number < 0)
        {
            throw new ArgumentException("Cannot calculate the square root of a negative number.");
        }

        if (number == 0)
        {
            return BigInteger.Zero;
        }

        var bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(number, 2)));
        BigInteger root = BigInteger.One << (bitLength / 2);

        while (!IsSquareRoot(number, root))
        {
            root += number / root;
            root /= 2;
        }

        return root;
    }

View on GitHub (pinned to 96e2905cab)