make a method that returns all prime numbers between the range of parameters in csharp

Here's an implementation of a method that takes in two integers (range parameters) and returns a list of all prime numbers within that range:

main.cs
public List<int> GetPrimesInRange(int start, int end)
{
    List<int> primes = new List<int>();

    for (int i = start; i <= end; i++)
    {
        if (IsPrime(i))
        {
            primes.Add(i);
        }
    }

    return primes;
}

private bool IsPrime(int number)
{
    if (number < 2)
    {
        return false;
    }

    for (int i = 2; i <= Math.Sqrt(number); i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }

    return true;
}
488 chars
33 lines

The GetPrimesInRange method initializes an empty list of integers and then loops through each number between start and end. For each number, it calls the IsPrime function to check if it is a prime. If the number is found to be prime, it is added to the list.

The IsPrime function returns true if the number is prime (greater than 1 and not divisible by any number other than itself and 1) and false otherwise. It does this by checking if the number is less than 2 (which is not a prime), and then looping through each integer up to the square root of the number and checking if it is divisible by that integer. If it is, the function returns false. If the loop completes, the function returns true.

Note that this implementation does not account for negative numbers.

gistlibby LogSnag