{"record":{"id":"f17f3e1da72441e6","repo":"TheAlgorithms/Python","slug":"factorial-recursive-not-defined-for-negative-val","errorCode":null,"errorMessage":"factorial_recursive() not defined for negative values","messagePattern":"factorial_recursive\\(\\) not defined for negative values","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/factorial.py","lineNumber":58,"sourceCode":"    Calculate the factorial of a positive integer\n    https://en.wikipedia.org/wiki/Factorial\n\n    >>> import math\n    >>> all(factorial_recursive(i) == math.factorial(i) for i in range(20))\n    True\n    >>> factorial_recursive(0.1)\n    Traceback (most recent call last):\n        ...\n    ValueError: factorial_recursive() only accepts integral values\n    >>> factorial_recursive(-1)\n    Traceback (most recent call last):\n        ...\n    ValueError: factorial_recursive() not defined for negative values\n    \"\"\"\n    if not isinstance(n, int):\n        raise ValueError(\"factorial_recursive() only accepts integral values\")\n    if n < 0:\n        raise ValueError(\"factorial_recursive() not defined for negative values\")\n    return 1 if n in {0, 1} else n * factorial_recursive(n - 1)\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n\n    n = int(input(\"Enter a positive integer: \").strip() or 0)\n    print(f\"factorial{n} is {factorial(n)}\")\n","sourceCodeStart":40,"sourceCodeEnd":69,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/factorial.py#L40-L69","documentation":"Raised by factorial_recursive() in maths/factorial.py when the argument n is a negative int. Factorial is undefined for negative integers, so the function rejects n < 0 with ValueError before recursing; without the guard the recursion would never terminate (n - 1 moves away from the base cases 0 and 1).","triggerScenarios":"Calling factorial_recursive(-1), factorial_recursive(-10), or any negative int. The isinstance check passes, then `if n < 0` raises immediately.","commonSituations":"Off-by-one bugs producing negative loop bounds, subtracting user-supplied values that go below zero, unvalidated command-line arguments, or sign errors in combinatorics formulas.","solutions":["Check n >= 0 before calling and clamp or reject the input at your own boundary.","Fix the upstream computation that produced the negative value (usually an off-by-one or a reversed subtraction).","If your domain genuinely needs negative-integer factorials, use a Gamma-function library (e.g. scipy.special.gamma), noting poles at negative integers."],"exampleFix":"# before\nn = len(items) - k  # can be negative when k > len(items)\nfactorial_recursive(n)\n\n# after\nn = len(items) - k\nif n < 0:\n    raise ValueError(f'k={k} exceeds len(items)={len(items)}')\nfactorial_recursive(n)","handlingStrategy":"validation","validationCode":"if n < 0:\n    raise ValueError(f'factorial undefined for negative n={n}')\nresult = factorial_recursive(n)","typeGuard":"def is_valid_factorial_arg(n: object) -> bool:\n    return isinstance(n, int) and n >= 0","tryCatchPattern":"try:\n    factorial_recursive(n)\nexcept ValueError as exc:\n    if 'negative' in str(exc):\n        n = 0  # clamp only if semantically acceptable\n    else:\n        raise","preventionTips":["Treat negative n as a caller bug: validate at the boundary and fail fast.","Use max(n, 0) only when clamping is an explicit product decision.","Watch for len(x) - k expressions that can dip below zero."],"tags":["math","factorial","negative-value","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}