Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 14-50 extracted from chapter Unsafe code, exceptions, anonymous methods, iterators


Listing 14-49<     > Listing 15-1


This listing can be compiled with the command line:
csc.exe /target:exe Example_14_50.cs
Errors: 0 Warnings: 0


Example_14_50.cs
using System;
using System.Collections.Generic;
class Program {
   static public IEnumerable<int> PipelineIntRange( int begin, int end ) {
      System.Diagnostics.Debug.Assert( begin < end );
      for int = begin; i <= end; i++ )
         yield return i;
   }
   static public IEnumerable<int> PipelinePrime( IEnumerable<int> input ) {
      using IEnumerator<int> e = input.GetEnumerator() ) {
         e.MoveNext();
         int prime = e.Current;
         // The first number of the list is a prime.
         Console.WriteLine( prime );
         if ( prime != ) {
            while ( e.MoveNext() ) {
               // Remove all multiple of the found prime.
               if ( e.Current % prime != )
                  yield return e.Current;
            }
         }
      }
   }
   const int = 100;
   static void Main() {
      // Apply the approximation of Gauss/de la Vallée Poussin 
      // to get the number of iterators.
      int N_PRIME = (int)Math.Floor( ((double)N)/Math.Log(N) );

      // Build a pipeline of N_PRIME PipelineIntegerRange chained with 
      // a PipelineIntegerRange. Each call to PipelinePrime yield an 
      // iterator object that we store.
      List<IEnumerable<int>> list = new List<IEnumerable<int>>();
      list.Add(PipelinePrime( PipelineIntRange( 2, N ) ) );
      forint i=1 ; i<N_PRIME ; i++ )
         list.Add( PipelinePrime(list[i-1]) );

      // Cascade the computation among iterators by yielding every
      // numbers between 2 and N.
      foreach int in list[N_PRIME-1] );
   }
}	
Copyright Patrick Smacchia 2006 2007