Iterator to obtain prime numbers

Source: Internet
Author: User

Using System. Collections;

Public class Primes // Primes Prime Number
{
# Region Property
Private long min;
Private long max;
# Endregion

# Region Constructor
Public Primes (): this (2,100)
{}
Public Primes (long minimum, long maximum)
{
If (min <2)
Min = 2;
Else
Max = maximum;
}
# Endregion

# Region Method
Public IEnumerator GetEnumerator ()
{
For (long possiblePrime = min; possiblePrime <= max; possiblePrime ++)
{
Bool isPrime = true; // The default value is a prime number, which is expressed as true.
For (long possibleFactor = 2; possibleFactor <= (long) Math. Floor (Math. Sqrt (possiblePrime); possibleFactor ++)
{
Long remainderAfterDivision = possiblePrime % possibleFactor;
If (remainderAfterDivision = 0)
{
IsPrime = false; // indicates the sum of values.
Break;
}
}
If (isPrime)
{
Yield return possiblePrime;
}
}
}
# Endregion
}
Public class Program
{
Static void Main (string [] args)
{
Primes primesFrom2To1000 = new Primes (2, 1000 );
Foreach (long I in primesFrom2To1000)
Console. Write ("{0}", I );
Console. ReadKey ();
}
}

Output: displays a result at a time, with a pause in the middle, instead of displaying all results at a time.

No matter whether the code is terminated before yieid is called, The iterator code returns a result at a time.

How do I display all the prime numbers in the range at a time ???

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.