# Prime Spiral Help

• Jun 14th 2009, 06:28 AM
VaguelyLost
Prime Spiral Help
Is there an equation (or 2) that will plot/generate a list of Coordinates (xy) for the locations of the Primes in a Prime Spiral:

e.g.
1st (2)Prime = (0, 1)
2nd (3)Prime = (1,1)
3rd (5)Prime = (-1,1)
and so on?

Thanks, V
• Aug 16th 2009, 06:02 AM
publicenumDirection { Right, Up, Left, Down };
publicbool IsPrime(int number)
{
if (number <= 0) // primes are positive
returnfalse;
if (number == 1) // debatable ???
returntrue;
if (number == 2) // 2 is the only even prime
returntrue;
if (number % 2 == 0) // exclude even numbers
returnfalse;
int sqrt = (int)Math.Sqrt(number);
for (int i = 3; i <= sqrt; i += 2)
{
if ((number % i) == 0)
{
returnfalse;
}
}
returntrue;
}
publicbool[] MarkPrimes(int max)
{
bool[] primes = newbool[max];
for (int i = 0; i < max; i++)
{
primes[i] = IsPrime(i);
}
return primes;
}
privatevoid DrawPrimeSpiral()
{
Graphics g = PictureBox.CreateGraphics();
SolidBrush brush = null;
PictureBox.Refresh();
int max = 313 * 313;
bool[] primes = MarkPrimes(max);
Color color = Color.Black;
int red = 0;
int green = 0;
int blue = 0;
int x = PictureBox.Width / 2;
int y = PictureBox.Height / 2;
int dx = 1;
int dy = 1;
Direction direction = Direction.Right;
int steps = 1;
int steps_in_directoin = steps;
for (int i = 0; i < max; i++)
{
// draw rectangle at new location in color shaded by primalogy value
green = primes[i] ? 255 : 0;
color =
Color.FromArgb(red, green, blue);
brush =
newSolidBrush(color);
g.FillRectangle(brush, x, y, dx, dy);
// has direction finished?
if (steps == 0)
{
// change direction
switch (direction)
{
caseDirection.Right: { direction = Direction.Up; } break;
caseDirection.Up: { direction = Direction.Left; steps_in_directoin++; } break;
caseDirection.Left: { direction = Direction.Down; } break;
caseDirection.Down: { direction = Direction.Right; steps_in_directoin++; } break;
}
steps = steps_in_directoin;
}
// move one step in current direction
switch (direction)
{
caseDirection.Right: x += dx; break;
caseDirection.Up: y -= dy; break;
caseDirection.Left: x -= dx; break;
caseDirection.Down: y += dy; break;
}
// one step done
steps--;
}
}