using System.Collections;
public class Primes //Primes 素数
{
#region Property
private long min;
private long max;
#endregion
#region Constructor
public Primes():this(2,100)
{ }
public Primes(long minimum, long maximum)
{
if (min < 2)
min = 2;
else
max = maximum;
}
#endregion
#region Method
public IEnumerator GetEnumerator()
{
for (long possiblePrime = min; possiblePrime <=max; possiblePrime++)
{
bool isPrime = true;//默认为素数,用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;
}
}
}
#endregion
}
public class Program
{
static void Main(string[] args)
{
Primes primesFrom2To1000 = new Primes(2, 1000);
foreach (long i in primesFrom2To1000)
Console.Write("{0}", i);
Console.ReadKey();
}
}
output: 一次显示一个结果,中间有暂停,而不是一次显示所有结果。
无论代码在yieid调用之前是否终止,迭代器代码都会一次返回一个结果。
如何将范围内的素数一次全部显示出来???