{"record":{"id":"1c929c8314f787c5","repo":"TheAlgorithms/Python","slug":"the-value-of-input-must-be-a-natural-number","errorCode":null,"errorMessage":"the value of input must be a natural number","messagePattern":"the value of input must be a natural number","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"dynamic_programming/minimum_squares_to_represent_a_number.py","lineNumber":29,"sourceCode":"    >>> minimum_squares_to_represent_a_number(37)\n    2\n    >>> minimum_squares_to_represent_a_number(21)\n    3\n    >>> minimum_squares_to_represent_a_number(58)\n    2\n    >>> minimum_squares_to_represent_a_number(-1)\n    Traceback (most recent call last):\n        ...\n    ValueError: the value of input must not be a negative number\n    >>> minimum_squares_to_represent_a_number(0)\n    1\n    >>> minimum_squares_to_represent_a_number(12.34)\n    Traceback (most recent call last):\n        ...\n    ValueError: the value of input must be a natural number\n    \"\"\"\n    if number != int(number):\n        raise ValueError(\"the value of input must be a natural number\")\n    if number < 0:\n        raise ValueError(\"the value of input must not be a negative number\")\n    if number == 0:\n        return 1\n    answers = [-1] * (number + 1)\n    answers[0] = 0\n    for i in range(1, number + 1):\n        answer = sys.maxsize\n        root = int(math.sqrt(i))\n        for j in range(1, root + 1):\n            current_answer = 1 + answers[i - (j**2)]\n            answer = min(answer, current_answer)\n        answers[i] = answer\n    return answers[number]\n\n\nif __name__ == \"__main__\":\n    import doctest","sourceCodeStart":11,"sourceCodeEnd":47,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/dynamic_programming/minimum_squares_to_represent_a_number.py#L11-L47","documentation":"Raised by minimum_squares_to_represent_a_number(number) when number != int(number), i.e. the value has a fractional part. The algorithm allocates an answers array indexed 0..number and iterates with integer indices, so non-integral inputs are rejected before anything runs. Note the type is not checked — 12.0 passes because 12.0 == int(12.0); this check happens before the negativity check.","triggerScenarios":"minimum_squares_to_represent_a_number(12.34) as in the doctest; any float with a fractional part; Decimal or Fraction values whose numeric comparison with int(number) fails. NaN also raises here since nan != int(nan) comparison is False.","commonSituations":"Math results (averages, sqrt outputs) passed without rounding; user input parsed as float from CLI or web forms; currency/measurements with decimal precision.","solutions":["Round or validate first: minimum_squares_to_represent_a_number(int(number)) if truncation is intended, or reject non-integral values upstream.","Use round(number) when the value should be integral but accumulated float error.","Validate at input boundaries with number.is_integer() for floats."],"exampleFix":"# before\ncount = minimum_squares_to_represent_a_number(value)  # value = 12.34 -> ValueError\n\n# after\nif not float(value).is_integer():\n    raise ValueError(f'expected integer, got {value}')\ncount = minimum_squares_to_represent_a_number(int(value))","handlingStrategy":"validation","validationCode":"if float(number).is_integer():\n    count = minimum_squares_to_represent_a_number(int(number))\nelse:\n    raise ValueError(f'{number!r} is not a natural number')","typeGuard":"def is_natural_number(value: object) -> bool:\n    return isinstance(value, (int, float)) and not isinstance(value, bool) and float(value).is_integer() and value >= 0","tryCatchPattern":"try:\n    count = minimum_squares_to_represent_a_number(number)\nexcept ValueError as exc:\n    if 'natural number' in str(exc):\n        raise ValueError(f'round or reject {number!r} before calling') from exc\n    raise","preventionTips":["Call float.is_integer() on computed values before passing to integer-domain algorithms.","Round deliberately (int() truncates toward zero; round() halves to even).","Keep measurement/scale math in integers from the start when possible."],"tags":["python","input-validation","dynamic-programming","math"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}