迭代器数素数,这个是我抄《C#入门经典》的
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace 迭代器数素数
{
public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public Primes(long minium, long maximum)
{
if (minium < 2)
minium = 2;
min = minium;
max = maximum;
}
public IEnumerator GetEnumerator()
{
for (long i = min; i < max; i++)
{
bool isPrime = true;
for (long j = 2; j <= (long)Math.Sqrt(i); j++)
{
long result;
result = i % j;
if (result == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
yield return i;
}
}
}
class Program
{
static void Main(string[] args)
{
long min,max;
Console.WriteLine("这是一个可以告知在一个确定范围内所有素数的程序。");
Console.WriteLine("请输入下限:");
min=Convert.ToInt64(Console.ReadLine());
Console.WriteLine("请输入上限:");
max=Convert.ToInt64(Console.ReadLine());
Primes myPrime = new Primes(min, max);
Console.WriteLine("以下是计算后得到的结果:");
foreach (long Prime in myPrime)
Console.WriteLine(Prime);
Console.WriteLine("谢谢使用。");
Console.ReadKey();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace 迭代器数素数
{
public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public Primes(long minium, long maximum)
{
if (minium < 2)
minium = 2;
min = minium;
max = maximum;
}
public IEnumerator GetEnumerator()
{
for (long i = min; i < max; i++)
{
bool isPrime = true;
for (long j = 2; j <= (long)Math.Sqrt(i); j++)
{
long result;
result = i % j;
if (result == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
yield return i;
}
}
}
class Program
{
static void Main(string[] args)
{
long min,max;
Console.WriteLine("这是一个可以告知在一个确定范围内所有素数的程序。");
Console.WriteLine("请输入下限:");
min=Convert.ToInt64(Console.ReadLine());
Console.WriteLine("请输入上限:");
max=Convert.ToInt64(Console.ReadLine());
Primes myPrime = new Primes(min, max);
Console.WriteLine("以下是计算后得到的结果:");
foreach (long Prime in myPrime)
Console.WriteLine(Prime);
Console.WriteLine("谢谢使用。");
Console.ReadKey();
}
}
}