TheAlgorithms/Go · error

x must be < n - given values are x=%d, n=%d

Error message

x must be < n - given values are x=%d, n=%d

What it means

splitInt distributes x items uniformly across n workers/channels; it requires x >= n so every slot gets at least one item (MonteCarloPiConcurrent passes total iterations vs worker count), and reports both values when the precondition fails.

Source

Thrown at math/pi/montecarlopi.go:78

// the number of points which where within the circle of center 0 and radius 1 (unit circle)
func drawPoints(n int, c chan<- int) {
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	inside := 0
	for i := 0; i < n; i++ {
		x, y := rnd.Float64(), rnd.Float64()
		if x*x+y*y <= 1 {
			inside++
		}
	}
	c <- inside
}

// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
	if x < n {
		return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n)
	}
	split := make([]int, n)
	if x%n == 0 {
		for i := 0; i < n; i++ {
			split[i] = x / n
		}
	} else {
		limit := x % n
		for i := 0; i < limit; i++ {
			split[i] = x/n + 1
		}
		for i := limit; i < n; i++ {
			split[i] = x / n
		}
	}
	return split, nil
}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Ensure the number of iterations is at least the number of workers before calling
  2. Clamp n to min(n, x) at the call site
  3. Skip the split entirely when x < n and handle x items in one batch
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at math/pi/montecarlopi.go:78 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/b3e49898b6a4c74f. Report an issue: GitHub.