This is good enough for my purposes, and I don't have time to focus on this now, However, it might be interesting for future visitors, so the question is how to make it faster by improving/rewriting.

Note: There may be confusion concerning whether I need a matrix populated with primes or one populated only with 0 and 1, 1 indicating the prime positions. Let's assume it doesn't matter. Maybe someone has a neat idea for the first representation that does not look good in the second one, so I'm leaving it open.

4 Answers
4

The function findPrimePosInBoundarys below finds out which primes are on which square and where they are on such squares. The coordinate is just an integer and for layer = 3, the coordinates indicate the following positions.

Here's my version using Join instead of Insert to build the spiral of numbers. By my measurements it's the fastest method for the smaller spiral of 200 layers, taking just 0.025 seconds to complete compared to 0.046 with Kuba's code and 0.055 with Jacob's code. But Jacob's solution wins hands down on the larger spiral with 1001 layers. That test takes just 1.14 seconds for Jacob's code while it takes 56 seconds for mine and 115 seconds for Kuba's.

(As an aside for future visitors: //Image//ColorNegate is faster than ArrayPlot, if you want to optimize every aspect of the problem.)

One point of confusion for some readers in regards to the code above could be that it is implemented as a closure which, as they say in the Mathematica Coobook, is "a bit outside garden-variety Mathematica". I'm referencing that book because, for those interested, its author has implemented a closure in an answer of his on this site. That example is simpler so it could be a good place to start learning how closures work.

One improvement of my code that I know but did not implement is that Range can list numbers in reversed order by having a negative step size. This could be used instead of Reverse.

Mathematica is a registered trademark of Wolfram Research, Inc. While the mark is used herein with the limited permission of Wolfram Research, Stack Exchange and this site disclaim all affiliation therewith.