Ulam+Prime+Spiral

Please enter your name and your solution.

Please place your code in a widget, with tags around it. The way to do that is to click the "EDIT" tab on the top right of the page, then click on the "Widget" button (it looks like a TV), then click on "Other HTML" on the lower left of the popup that appears. Paste in your Mathematica code with before it and after it. Andy Rundquist (graphical solution instead of a table. What I don't like is you set the number of turns, not the number of integers to do. With 20 turns you get 421 integers. It colors the primes red and all others black. I'm sure it can be optimized.) **UPDATE:** I added a 45 degree rotation to the spiral, while maintaining the orientation of the integers. I think it's easier to see the primes on horizontal and vertical lines this way. media type="custom" key="10323958"

Eric Brodeur: I used a variation on Transpose, where we Rotate a given matrix (table) -- and then repeatedly apply this to a Partitioned Range list to wrap the range in a spiral. code Rot90[m_] := Map[Reverse, Transpose[m]]

Rot270[m_] := Transpose[Map[Reverse, m]]

IntegerSpiral[N_] := Fold[Append[Rot270@#1, Reverse@#2] &, – , Most@Flatten[ Table[Partition[Range[n^2 - n + 1, n^2 + n], n], {n, 2 N}], 1]] code Here are some Grid functions to display labeled Ulam spirals: code UlamSpiralGrid[N_] := Grid[#, Frame -> All, ItemSize -> {.9, 1}] &@ IntegerSpiral[N] /. {x_ /; PrimeQ[x] :> Item[Style[x, Tiny], Background -> LightRed], z_ /; IntegerQ[z] :> Item[Style[z, Tiny]]}

UlamSpiralGrid2[N_] := Grid[#, Frame -> All, ItemSize -> {.05, .05}] &@ Boole[PrimeQ[IntegerSpiral[N]]] /. {1 ->   Item[Style[1, Tiny], Background -> LightRed], 0 -> Item[Style[0, Tiny]]} code

Finally, here is code to get raw data of various sizes, and use ArrayPlot for a classic Ulam spiral plot -- as well as measure timing performance. Clearly, this solution is sub-optimal, as it is exponentially expensive. code sizes = {10, 20, 50, 100, 200, 500, 1000, 2000, 5000};

{timings, spiraldata} = Transpose@ Table[Module[{t, s}, {t, s} = Timing@IntegerSpiral[N]; {{N, t}, N -> s}], {N, sizes}];

ListLogLogPlot[timings, Joined -> True, Mesh -> All, AxesLabel -> {"N", "seconds"}]

ArrayPlot[Boole[PrimeQ[100 /. spiraldata]], Mesh -> True, MeshStyle -> Directive[Thin, Gray, Opacity[0.2]], ImageSize -> 500] code