TheAlgorithms/C-Sharp · error · ArgumentOutOfRangeException

k must be at least 1.

Error message

k must be at least 1.

What it means

The KNearestNeighbors constructor rejects a neighbor count k below 1. k controls how many nearest training samples vote on a classification, so k < 1 is meaningless and would break the top-k selection in Predict. The library throws ArgumentOutOfRangeException at construction time to fail fast.

Solutions

  1. Pass k >= 1 to the constructor (k = 1 is valid for nearest-neighbor).
  2. Clamp or validate user/config-supplied k before constructing: Math.Max(1, configuredK).
  3. Check any computed k (e.g. dataset.Count / someFactor) for rounding down to 0 and enforce a minimum of 1.

Example fix

// before
int k = samples.Count / 10; // can be 0 for small datasets
var knn = new KNearestNeighbors(k);
// after
int k = Math.Max(1, samples.Count / 10);
var knn = new KNearestNeighbors(k);
Defensive patterns

Strategy: validation

Validate before calling

if (k < 1)
    throw new ArgumentException("k must be at least 1 before constructing KNearestNeighbors.");
var knn = new KNearestNeighbors(k);

Try / catch

try
{
    var knn = new KNearestNeighbors(k);
}
catch (ArgumentOutOfRangeException ex)
{
    // ex.ParamName == "k": fall back to a sane default
    var knn = new KNearestNeighbors(3);
}

Prevention

When it happens

Trigger: Calling new KNearestNeighbors(0), new KNearestNeighbors(-1), or any k derived from a computation/user input that resolves to less than 1.

Common situations: k read from a config file or CLI defaulting to 0 when unset; computing k as a fraction of dataset size with integer division rounding down to 0 on tiny datasets; off-by-one loops generating k = 0.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/2f920ac39979ae83. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/MachineLearning/KNearestNeighbors.cs:28

/// </summary>
/// <typeparam name="TLabel">
/// The type of the label used for classification. This can be any type that represents the class or category of a sample.
/// </typeparam>
public class KNearestNeighbors<TLabel>
{
    private readonly List<(double[] Features, TLabel Label)> trainingData = new();
    private readonly int k;

    /// <summary>
    /// Initializes a new instance of the <see cref="KNearestNeighbors{TLabel}"/> classifier.
    /// </summary>
    /// <param name="k">Number of neighbors to consider for classification.</param>
    /// <exception cref="ArgumentOutOfRangeException">Thrown if k is less than 1.</exception>
    public KNearestNeighbors(int k)
    {
        if (k < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(k), "k must be at least 1.");
        }

        this.k = k;
    }

    /// <summary>
    /// Calculates the Euclidean distance between two feature vectors.
    /// </summary>
    /// <param name="a">First feature vector.</param>
    /// <param name="b">Second feature vector.</param>
    /// <returns>Euclidean distance.</returns>
    /// <exception cref="ArgumentException">Thrown if vectors are of different lengths.</exception>
    public static double EuclideanDistance(double[] a, double[] b)
    {
        if (a.Length != b.Length)
        {
            throw new ArgumentException("Feature vectors must be of the same length.");
        }

View on GitHub (pinned to 96e2905cab)