代码改变世界

类和迭代器

2012-04-27 21:41  精诚所至 金石为开  阅读(246)  评论(0编辑  收藏  举报

迭代器怎么用。

Primes类。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace aa
{
	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;
			}
			min=minimum;
			max=maximum;
		}
		public IEnumerator GetEnumerator()
		{
			for(long possiblePrime=min;possiblePrime<=max;possiblePrime++)
			{
				bool isPrime=true;
				for(long possibleFactor=2;possiblePrime<=(long)Math.Floor(Math.Sqrt(possiblePrime));possibleFactor++)
				{
					long remainderAfterDivision=possiblePrime % possibleFactor;
					if (remainderAfterDivision==0)
					{
						isPrime=false;
						break;
					}
				}
				if(isPrime)
				{
					yield return possiblePrime;
				}
			}
		}
	}
}

progress.cs.

using System;
namespace aa
{
	class Program
	{
		public static void Main(string[] args)
		{
			Primes primesFrom2To1000=new Primes(2,1000);
			foreach (long i in primesFrom2To1000)
				Console.Write("{0}",i);
			Console.ReadKey();
		}
	}
}