find primes in csharp

To find prime numbers in c#, we can use a simple brute-force approach where we test if a number is divisible by any number less than its square root. If it is not divisible by any number less than its square root, then it is a prime number.

Here is the simple code to find prime numbers in c#:

main.cs
public static 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;
}
220 chars
14 lines

The code above takes an integer number as input and returns a boolean indicating whether or not the number is prime.

To find all prime numbers between a given range, we can use the following code:

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

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

    return primes;
}
216 chars
13 lines

The code above takes two integers as input (start and end) and returns a list of prime numbers between the start and end range. It uses the IsPrime method defined earlier to check if a number is prime or not.

gistlibby LogSnag