[Tutor] Primes on a two-dimensional plane in the form of a rectangular spiral

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 9 Apr 2001 09:16:06 +0200


On  0, Julieta <julieta_rangel@hotmail.com> wrote:
> The primes, 2,3,4,5,7, . . . can be arranged on a two-dimensional plane in the form of a rectangular spiral.
> <-represents left   -> represents right    ^represents up     | represents down
> 
> 59 <-  53 <-  47  <-  43    <-    41
>                                              ^
>         11 <-   7    <-   5   <-     37
>           |                    ^            ^
>         13        2   ->   3           31
>           |                                 ^ 
>         17  ->  19  ->  23   ->    29
> 
> How could I write a program which inputs integers M and N and outputs the
> value of the number at location (M, N) on the plane?  The initial 2 is
> stored at position (0,0).  This means that an input of ( 0, 0 ) should
> output 2.  An input of, say, ( -1, 1) should output 11; an input of (-1,2)
> should output 53, and so on.

What an odd problem. Is this a homework assignment?

At first it looks like the way to do this is
a) Find out from the position you get which prime you need
b) Find that prime

On a closer look, the way to find prime n is to build up a list of them,
growing it until you've found the nth one. It would be easy to keep track of
the position of that prime as well, stopping when we arrive at the right
point.

If you have the Python source distribution, there is a prime number program
in Demos/scripts/primes.py.

Change the primes function to primes(x, y) for the position and let it
always start at min=2. Initialize cur_x and cur_y to 0, 0, for the start
position. Change the loop into something like "while (x,y) != (cur_x,
cur_y)" and put some code after primes.append(i) that moves the position
(cur_x, cur_y) around appropriately.

In the end, primes[-1] has the answer.

-- 
Remco Gerlich