迭代器示例

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++;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值