42. Yielding primes

A method can use the yield keyword to return a value to the calling code and then resume execution later. The calling code receives the results as an IEnumerable and can loop through them as needed.

The following method yields primes:

// Yield numPrimes primes.
private IEnumerable<long> Primes(int numPrimes)
{
// Treat 2 separately.
yield return 2;
if (numPrimes == 1) yield break;

int count = 1;
for (long i = 3; ; i += 2)
{
if (IsPrime(i))
{
yield return i;
if (++count == numPrimes) yield break;
}
}
}

The method first uses a yield return statement to return the first prime, 2. It then loops over odd numbers, looking for other primes.

Inside the loop, the method uses the IsPrime method to see if the current value is prime. If the value is prime, the method uses yield return to send it to the calling code. Then, if the method has returned the required number of primes, it uses a yield break statement to stop yielding values.

The main program uses the following code snippet to display the primes:

int numPrimes = int.Parse(numPrimesTextBox.Text);
int i = 1;
foreach (long prime in Primes(numPrimes))
primesListBox.Items.Add(i++.ToString() + ": " + prime);

This code first gets the desired number of values entered by the user. It then uses a foreach loop to iterate through the primes returned by Primes(numPrimes) and adds them to the form's list box. It uses the count variable i to display each prime's position in the primes list, along with its value.

Download the YieldingPrimes example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.203.43