using System;
using System.Collections.Generic;
namespace demoIterators
{
class Program
{
static void Main(string[] args)
{
sczs(-100);
sczs(1);
sczs(2);
sczs(3);
sczs(10000);//结果根据需要计算,50个以后的数据并未计算
sczs(100);
}
static void sczs(int cMax)
{
Console.WriteLine("输出 {0} 以内的质数(最多50个):", cMax);
int c = 0;
foreach (int i in zs(cMax))
{
Console.Write("{0}\t", i);
if (++c > 50) break;
}
Console.WriteLine();
Console.ReadKey();
}
//返回质数系列。!!!迭代器内不能抛出异常
static IEnumerable<int> zs(int cMax)
{
if (cMax > 0) yield return 1;
if (cMax > 1) yield return 2;
if (cMax > 2) yield return 3;
int i = 5;
while (i <= cMax)
{
int t = (int)Math.Sqrt(i); bool s = true;
for (int j = 2; j <= t; j++) { if (i % j == 0) { s = false; break; } }
if (s) yield return i;
i++;
}
}
}
}
迭代器示例
最新推荐文章于 2022-06-16 16:03:17 发布