#1,197 – Iterator Can Generate Enumerable of Infinite Length

An iterator can be written to generate an enumerable sequence of infinite length.  The iterator will execute for as long as client code continues to request the next element in the sequence.

Below is a simple iterator that generates prime numbers.  Note that we can still use the iterator, although its implementation includes an infinite loop.  The loop will execute only as many times as needed.

        static void Main(string[] args)
        {
            Console.Write("Enter limit:");
            int limit = int.Parse(Console.ReadLine());

            foreach (int p in AllPrimes())
            {
                if (p > limit)
                    break;
                Console.WriteLine(p);
            }

            Console.ReadLine();
        }

        private static IEnumerable<int> AllPrimes()
        {
            List<int> primesSoFar = new List<int>();
            primesSoFar.Add(2);
            yield return 2;
            primesSoFar.Add(3);
            yield return 3;

            int testPrime = 5;
            while (true)
            {
                bool isPrime = true;
                foreach (int n in primesSoFar)
                {
                    if (testPrime % n == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }

                if (isPrime)
                {
                    primesSoFar.Add(testPrime);
                    yield return testPrime;
                }

                testPrime += 2;
            }
        }

1197-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: