The short answer is: if you have an object that calls an internal object, you increase the stack trace by 1. Thus, if you have 1000 objects nested inside each other, each of which calls its own internal object, you end up with overflow stack.
Here's how to create primes using nested iterators:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Program p = new Program(); IEnumerator<int> primes = p.AllPrimes().GetEnumerator(); int numberOfPrimes = 1000; for (int i = 0; i <= numberOfPrimes; i++) { primes.MoveNext(); if (i % 1000 == 0) { Console.WriteLine(primes.Current); } } Console.ReadKey(true); } IEnumerable<int> FilterDivisors(IEnumerator<int> seq, int num) { while (true) { int current = seq.Current; if (current % num != 0) { yield return current; } seq.MoveNext(); } } IEnumerable<int> AllIntegers() { int i = 2; while (true) { yield return i++; } } IEnumerable<int> AllPrimes() { IEnumerator<int> nums = AllIntegers().GetEnumerator(); while (true) { nums.MoveNext(); int prime = nums.Current; yield return prime;
There is no recursion, but the program will throw an exception after about 150,000 primes.
Juliet
source share