[csharp]
<pre name="code" class="csharp">Primes.cs文件</pre>
<pre></pre>
<pre name="code" class="csharp">using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Primes
{
private long min;
private long max;
public Primes() : this(2, 100)
{ }
public Primes(long minimum, long maximum)
{
if (min < 2)
min = 2;
else
min = minimum;
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;
}
}
}
}
}
</pre><pre name="code" class="csharp"><pre name="code" class="csharp">Program.cs文件</pre>
<pre></pre>
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
<span style="color:#ff0000;"> Primes primesFrom2To1000 = new Primes(2, 10000); //此處定義范圍</span>
foreach (long i in primesFrom2To1000)
Console.Write("{0}",i+"\t");
Console.WriteLine();
Console.ReadKey();
}
}
}
</pre><br>
</pre>