Returns a list of primes, based on the Sieve of Eratosthenes - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Returns a list of primes, based on the Sieve of Eratosthenes

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;//from ww w  .  j a va  2  s.  c om

public class Main{
        /// <summary>
        /// Returns a list of primes, based on the Sieve of Eratosthenes
        /// </summary>
        /// <param name="exclusiveMax">Exclusive upperlimit, for example 100 would give primes up to 99</param>
        /// <returns>A list of primes, or empty list otherwise</returns>
        /// <remarks>Exclusive max, must be lower then Int32.maxValue</remarks>
        public static List<int> SieveOfEratosthenes(int exclusiveMax)
        {
            List<int> primes = new List<int>();
            // Sieve works from 2 and up, return empty on negative, zero, or 1 as max. Returns empty list
            if (exclusiveMax < 2) { return primes; }

            // SIEVE!
            BitArray nonPrimes = new BitArray(exclusiveMax);                // iterate on list, false = prime, true is nonprime
            int maxDivisor = Convert.ToInt32(System.Math.Sqrt(exclusiveMax)) + 1;  // maximum divisor/factor is the squareroot of exclusivemax
            for (int i = 2; i < maxDivisor; i++)
            {   // checking out all factors
                if (!nonPrimes[i])
                {   // this number is still set as a prime, strike off all multiples of this number
                    for (int j = i + i; j < exclusiveMax; j = j + i) { nonPrimes[j] = true; }
                }
            }
            for (int i = 2; i < exclusiveMax; i++)
            {   // iterate on list, 0 = prime, 1 is nonprime
                if (!nonPrimes[i]) { primes.Add(i); }
            }
            return primes;
        }
}

Related Tutorials