Python

 

 

Introduction:

The Ulam Spiral is a visual representation of prime numbers arranged in a spiral pattern. In this tutorial, we will learn how to generate the Prime Spiral (Ulam Spiral) using Python. The prime spiral displays prime numbers in a grid, starting at the center and spiraling outward. The idea is to check each number, plot it in the grid, and highlight prime numbers. This method offers an interesting visualization of prime number distribution.

Objective:

The goal is to write a Python program that will generate the Prime Spiral and visualize it. The program will take a limit of numbers and plot them in a spiral, highlighting the prime numbers in a different color.

Python Code to Generate Prime Spiral:

# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Function to check if a number is prime
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(np.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

# Function to create the prime spiral
def generate_prime_spiral(size):
    # Create an empty grid
    grid = np.zeros((size, size))
    
    # Set starting point (center of the grid)
    x, y = size // 2, size // 2
    grid[x, y] = 1
    prime_numbers = [1]
    num = 2

    # Directions for moving in the spiral (right, up, left, down)
    directions = [(0, 1), (-1, 0), (0, -1), (1, 0)]  
    direction = 0
    steps = 1
    while num <= size * size: for _ in range(2): for _ in range(steps): # Move in the current direction x += directions[direction][0] y += directions[direction][1] if is_prime(num): grid[x, y] = 1 else: grid[x, y] = 0 prime_numbers.append(num) num += 1 # Change direction (right -> up -> left -> down)
            direction = (direction + 1) % 4
        steps += 1
    
    return grid

# Function to plot the prime spiral
def plot_prime_spiral(size):
    grid = generate_prime_spiral(size)
    plt.figure(figsize=(10, 10))
    plt.imshow(grid, cmap='Greys', interpolation='nearest')
    plt.title('Prime Spiral (Ulam Spiral)')
    plt.axis('off')  # Hide axis
    plt.show()

# Call function with a given size (must be odd for a centered spiral)
plot_prime_spiral(101)  # Try different values like 101, 201, etc.

Explanation of the Program Structure:

The program consists of several key components:

  • is_prime(n): This function checks if a number is prime by checking divisibility up to the square root of the number.
  • generate_prime_spiral(size): This function generates the prime spiral. It initializes an empty grid and places numbers in a spiral pattern, checking each number for primality and marking primes on the grid.
  • plot_prime_spiral(size): This function uses matplotlib to display the prime spiral grid visually. Prime numbers are shown in white and non-prime numbers in black.

The main logic of the spiral movement is implemented by changing directions (right, up, left, down) in a cyclic order. The spiral size can be adjusted by passing different values to plot_prime_spiral(), with odd numbers being preferable for a centered spiral.

How to Run the Program:

Follow these steps to run the Python program:

  1. Install the required library by running pip install matplotlib numpy.
  2. Copy the Python code provided above into a Python file (e.g., prime_spiral.py).
  3. Run the program using a Python interpreter: python prime_spiral.py.
  4. Make sure you have Python 3.x installed on your system.
  5. The program will generate a window showing the Prime Spiral pattern. You can adjust the grid size in the plot_prime_spiral() function.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)