{"record":{"id":"29b2909c36fa85d5","repo":"trekhleb/javascript-algorithms","slug":"the-method-supports-only-positive-integers","errorCode":null,"errorMessage":"The method supports only positive integers","messagePattern":"The method supports only positive integers","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/algorithms/math/square-root/squareRoot.js","lineNumber":12,"sourceCode":"/**\n * Calculates the square root of the number with given tolerance (precision)\n * by using Newton's method.\n *\n * @param number - the number we want to find a square root for.\n * @param [tolerance] - how many precise numbers after the floating point we want to get.\n * @return {number}\n */\nexport default function squareRoot(number, tolerance = 0) {\n  // For now we won't support operations that involves manipulation with complex numbers.\n  if (number < 0) {\n    throw new Error('The method supports only positive integers');\n  }\n\n  // Handle edge case with finding the square root of zero.\n  if (number === 0) {\n    return 0;\n  }\n\n  // We will start approximation from value 1.\n  let root = 1;\n\n  // Delta is a desired distance between the number and the square of the root.\n  // - if tolerance=0 then delta=1\n  // - if tolerance=1 then delta=0.1\n  // - if tolerance=2 then delta=0.01\n  // - and so on...\n  const requiredDelta = 1 / (10 ** tolerance);\n\n  // Approximating the root value to the point when we get a desired precision.","sourceCodeStart":1,"sourceCodeEnd":30,"githubUrl":"https://github.com/trekhleb/javascript-algorithms/blob/85293e3e2b88f4d2ce330d956b139cf628aa1e82/src/algorithms/math/square-root/squareRoot.js#L1-L30","documentation":"squareRoot(number, tolerance) computes real square roots only: the first guard throws when number is negative because the implementation explicitly avoids complex-number manipulation. Zero is handled as a special case (returns 0), and despite the message saying 'positive integers' the actual check is just number < 0, so any non-negative float is accepted. The message wording is broader than the enforced rule.","triggerScenarios":"squareRoot(-4); squareRoot(a * a - b * b) when b > a; squareRoot(b * b - 4 * a * c) with a negative discriminant; passing unclamped user or sensor input that can go below zero.","commonSituations":"Numeric code where a value that should be non-negative turns negative through rounding, operand ordering, or bad data (squared distances, variances, discriminants), and unit tests that enumerate negative inputs.","solutions":["Check the value before calling: if (n < 0) handle the no-real-root case explicitly (return NaN, branch, or report)","If negativity signals a bug, fix the upstream math (e.g. wrong operand order in a difference of squares)","For discriminants, branch on the sign before taking the root","If complex results are genuinely needed, use a complex-number library instead of this function"],"exampleFix":"// before\nimport squareRoot from './src/algorithms/math/square-root/squareRoot';\nconst root = squareRoot(b * b - 4 * a * c);\n// throws when the discriminant is negative\n\n// after\nconst discriminant = b * b - 4 * a * c;\nconst root = discriminant >= 0 ? squareRoot(discriminant) : NaN;","handlingStrategy":"validation","validationCode":"if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n  return NaN; // no real root\n}\nconst root = squareRoot(value);","typeGuard":"const isRealRootable = (n) => typeof n === 'number' && !Number.isNaN(n) && n >= 0;","tryCatchPattern":"try {\n  r = squareRoot(x);\n} catch (e) {\n  if (e.message === 'The method supports only positive integers') {\n    r = NaN; // negative input: no real root\n  } else {\n    throw e;\n  }\n}","preventionTips":["Branch on sign before taking the root of any computed expression","Treat negative inputs as logic bugs and assert on them in dev builds","Unit-test 0, negative and fractional inputs around every root call"],"tags":["math","square-root","domain-error","validation"],"backgroundTag":"math-domain-error","analyzedSha":"85293e3e2b88f4d2ce330d956b139cf628aa1e82","analyzedAt":"2026-08-24T05:59:10.417Z","schemaVersion":2},"datasetVersion":"2026-08-24T07:17:09.176Z"}