This example modifies the program in Use a bitmap to visualize primes in C# to let you visualize odd primes. It creates an `is_prime` array like the previous example does, but it makes the array twice as large as before. It then only displays the odd numbers in the bitmap.

In other words, the previous example makes a bitmap that uses a red pixel if the values 0, 1, 2, 3, 4, and so forth are prime. This version’s bitmap uses a red pixel if the values 1, 3, 5, 7, 9, and so forth are prime. That removes all of the black pixels that would represent multiples of two.

The following code shows how the program creates its `is_prime` array.

`// Make a sieve.
int num_rows = int.Parse(txtNumRows.Text);
int num_cols = int.Parse(txtNumColumns.Text);
if (num_cols % 2 != 0) num_cols++; // Make it even.
int length = 2 * num_rows * num_cols;
bool[] is_prime = MakeSieve(length);
// Make the bitmap.
Bitmap bm = MakeBitmap(is_prime, num_cols, num_rows);`

This is similar to the code used by the previous example except it doubles the number of values in the sieve.

The following code shows how the program creates its bitmap.

`// Make a bitmap showing the primes.
private Bitmap MakeBitmap(bool[] is_prime, int wid, int hgt)
{
// Make the bitmap.
Bitmap bm = new Bitmap(wid, hgt);
// Set the pixels.
int index = 1;
for (int y = 0; y < hgt; y++)
{
for (int x = 0; x < wid; x++)
{
if (is_prime[index])
bm.SetPixel(x, y, Color.Red);
else
bm.SetPixel(x, y, Color.Black);
index += 2;
}
}
// Fix 1.
bm.SetPixel(0, 0, Color.Blue);
return bm;
}`

This is also similar to the previous version, except it only plots the odd-numbered values. After it draws the bitmap, it colors the upper left pixel blue to represent the value 1, which technically isn’t prime.

See the previous example for observations about the results.

##
About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.

Pingback: Find runs of composite numbers (non-primes) in C# -