TheAlgorithms/Go · error

input argument must be non-negative integer

Error message

input argument must be non-negative integer

What it means

Sentinel error returned by both Iterative and Recursive factorial when n < 0; the factorial is only defined for non-negative integers, so any negative input triggers this guard before computation begins.

Source

Thrown at math/factorial/factorial.go:17

// factorial.go
// description: Calculating factorial
// details:
// The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n - [Factorial](https://en.wikipedia.org/wiki/Factorial)
// time complexity: O(n)
// space complexity: O(1)
// author(s) [red_byte](https://github.com/i-redbyte)
// see factorial_test.go

// Package factorial describes algorithms Factorials calculations.
package factorial

import (
	"errors"
)

var ErrNegativeArgument = errors.New("input argument must be non-negative integer")

// Iterative returns the iteratively brute forced factorial of n
func Iterative(n int) (int, error) {
	if n < 0 {
		return 0, ErrNegativeArgument
	}
	result := 1
	for i := 2; i <= n; i++ {
		result *= i
	}
	return result, nil
}

// Recursive This function recursively computes the factorial of a number
func Recursive(n int) (int, error) {
	if n < 0 {
		return 0, ErrNegativeArgument
	}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Validate n>=0 before computing
  2. Use the gamma function if you need factorials of negative/non-integer values
  3. Return a zero value with a domain-specific message for invalid input
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at math/factorial/factorial.go:17 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/2bfed6a634e66063. Report an issue: GitHub.