How to Find Prime Numbers in an Array in C#?

Do you want to find prime numbers in a C# array? In this C# tutorial, I will explain how to find prime numbers in an array in C#.

To find prime numbers in an array in C#, iterate through the array and check each number with a function that determines if it’s prime. This function should return false for numbers less than 2 and then check divisibility up to the square root of the number, returning true only for numbers that are not divisible by any other number except 1 and themselves.

Find Prime Numbers in an Array in C#

Now, let us write a program to find prime numbers in an array in C#.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, and so on.

To check if a number is prime, we need to test if it is not divisible by any number less than itself and greater than 1. The most efficient way to do this is to check divisibility up to the square root of the number.

using System;
using System.Collections.Generic;

class PrimeFinder
{
    static void Main()
    {
        int[] array = {2, 3, 4, 5, 6, 7, 11, 13, 17, 18, 19, 23, 29};
        List<int> primes = FindPrimesInArray(array);

        Console.WriteLine("Prime numbers in the array are:");
        foreach (int prime in primes)
        {
            Console.WriteLine(prime);
        }
    }

    static List<int> FindPrimesInArray(int[] arr)
    {
        List<int> primeList = new List<int>();
        foreach (int num in arr)
        {
            if (IsPrime(num))
            {
                primeList.Add(num);
            }
        }
        return primeList;
    }

    static bool IsPrime(int num)
    {
        if (num <= 1) return false;
        if (num <= 3) return true;

        if (num % 2 == 0 || num % 3 == 0) return false;

        for (int i = 5; i * i <= num; i += 6)
        {
            if (num % i == 0 || num % (i + 2) == 0)
                return false;
        }
        return true;
    }
}
  1. Main Method: We define an array of integers and call FindPrimesInArray to filter out the primes.
  2. FindPrimesInArray Method: This method iterates through the array and uses IsPrime to check if each number is prime.
  3. IsPrime Method: It efficiently checks if a number is prime. We handle edge cases for numbers less than 4 and then check divisibility starting from 5, incrementing by 6 each time (since any prime number greater than 3 can be written in the form of 6k±1).

Once you run the code using a console application in C#, you can see the output in the below screenshot.

find prime numbers in an array in c#

Conclusion

Finding prime numbers in an array using C# is a great way to understand basic programming concepts and number theory. In this C# tutorial, I have explained how to find prime numbers in an array in C# using the above simple program.

You may also like: