Wednesday, October 8, 2025

The Ulam Spiral

The Ulam spiral or prime spiral is a graphical depiction of the set of prime numbers. It emphasizes the striking appearance in the spiral of prominent diagonal, horizontal, and vertical lines containing large numbers of primes.

How to construct Ulam Spiral?
The number spiral is constructed by writing the positive integers in a spiral arrangement on a square lattice, as shown.

The Ulam spiral is produced by specially marking the prime numbers—for example by circling the primes or writing only the primes or by writing the prime numbers and non-prime numbers in different colors—to obtain a figure like the one below.

Code to Generate Prime Number
#importing the required libraries
import math
import itertools

def primes():
    yield 2
    primesSoFar = [2]
    for candidate in itertools.count(3, 2):
        for prime in (i for i in primesSoFar if i  100:      
            break
        print(p)

if __name__ == "__main__":
    main()

But that’s not what we wanted. We wanted to generate Ulam spiral, isn’t it?
Its just getting started so the next step is to generate the prime spiral ; to generate one pixel for each natural number, black or white, depending on whether the number is a prime or not. To generate such plot we will use the matplotlib library of python and numpy for mathematical purposes.

So now the question is how should we approach? It’s quite a simple idea. First we have to generate a array of prime numbers of size ‘n^2’. Then create an array of boolean values: 1 for prime, 0 for composite of same size ‘n^2’. The next step should be convert the second array of boolean values to spiral the values clockwise out from the center and to do so we can proceed with the following steps :

1: Generate an array with elements containing ‘n*n’ and then reshape the array to matrix form of order ‘n X n’.

2: Create another empty list then append the first row of the matrix generated in step 1.

3: Remove the first row (the one we’ve just appended to spiral).

4: Rotate the rest of the array anticlockwise.

5: Make a flat array of indices spiralling into the array.

6: Index into a flattened version of our target array with spiral indices.

And after following the steps you are good to go and lastly just plot the array we got after the following operations using matplotlib as mentioned above. The code is given down below still i would highly recommend you to try this out first by yourself then dig in to the code.




# Python code to print Ulam's spiral
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
  
# function to plot out the ulam spiral
def make_spiral(arr):
    nrows, ncols= arr.shape
    idx = np.arange(nrows*ncols).reshape(nrows,ncols)[::-1]
    spiral_idx = []
    while idx.size:
        spiral_idx.append(idx[0])
  
        # Remove the first row (the one we've
        # just appended to spiral).
        idx = idx[1:]
  
        # Rotate the rest of the array anticlockwise
        idx = idx.T[::-1]
  
    # Make a flat array of indices spiralling 
    # into the array.
    spiral_idx = np.hstack(spiral_idx)
  
    # Index into a flattened version of our 
    # target array with spiral indices.
    spiral = np.empty_like(arr)
    spiral.flat[spiral_idx] = arr.flat[::-1]
    return spiral
  
# edge size of the square array.
w = 251
# Prime numbers up to and including w**2.
primes = np.array([n for n in range(2,w**2+1) if all(
                        (n % m) != 0 for m in range(2,int(np.sqrt(n))+1))])
  
# Create an array of boolean values: 1 for prime, 0 for composite
arr = np.zeros(w**2, dtype='u1')
arr[primes-1] = 1
  
# Spiral the values clockwise out from the centre
arr = make_spiral(arr.reshape((w,w)))
  
plt.matshow(arr, cmap=cm.binary)
plt.axis('off')
plt.show()


For a better understanding of this mathematical concept prefer refer to this video.

This article is contributed by Subhajit Saha. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32342 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6712 POSTS0 COMMENTS
Nicole Veronica
11875 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6833 POSTS0 COMMENTS
Ted Musemwa
7092 POSTS0 COMMENTS
Thapelo Manthata
6786 POSTS0 COMMENTS
Umr Jansen
6789 POSTS0 COMMENTS