iterator..... s
i am new this whole thing.... and its quiet hard for me
to get to grips with it....
The following code is from a book , so hardly my own work...
Although the code for calculating prime numbers is a bit tricky
to follow, i don't think thats the purpose of the code... as such
What i find hard to get is the way it works... i mean..... there is
no explicit call... to GetEnumerator()
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace c11ex03
{
public class primes
{
private long min;
private long max;
// what is the purpose of the default constructor
// on the line below...
// is it used since the non default constructor
//is what sets up the min and max values.
//i dont know why the code uses ... this(2, 100)
//when the primes are between 2 and 1000, it seems like a typo.
// but when new to coding i could be wrong.
// and in anycase this constructor has no body...
// default constructor seem pointless....what can a function or //constuctor with no body be of any use.. in fact i am sure
// that c# can create them by default... what ever that means.
//quoting for visual c#: "When you define a class in C#, there is
// no need to to "define" assocciated constructors and destructors
//because the base class System.Object provides default implementation
// for you... so when do you and when dont you..
// as mentioned in any case the default one is bypassed.. or is it.
public primes(): this(2, 100)
{
}
public primes(long minium, long maximum)
{
if (min < 2)
min = 2;
min = minium;
max = maximum;
}
public IEnumerator GetEnumerator()
{
for (long possiblePrime = min; possiblePrime <= max; possiblePrime++)
{
bool isPrime = true;
for (long possibleFactor = 2; possibleFactor <=
(long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
{
long remainderAfterDivision = possiblePrime % possibleFactor;
if (remainderAfterDivision == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
yield return possiblePrime;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace c11ex03
{
class Program
{
static void Main(string[] args)
{
primes primesFrom2To1000 = new primes(2, 1000);
foreach (long i in primesFrom2To1000)
Console.Write("{0} ", i);
Console.ReadKey();
}
}
}
|