Golang

 

Introduction

The Ulam spiral (or prime spiral) is a graphical representation of prime numbers arranged in a spiral pattern. This visualization helps in understanding the distribution of prime numbers. The program we will create in the Go programming language generates a prime spiral by filling a 2D grid with numbers, marking prime numbers, and arranging them in a spiral pattern.

Objective

The objective of this tutorial is to create a Prime Spiral (Ulam Spiral) using the Go programming language. We will generate a grid of numbers in a spiral shape and then identify the prime numbers. These prime numbers will be highlighted to form the prime spiral visualization.

Code to Create Prime Spiral in Go


        package main

        import (
            "fmt"
            "math"
            "os"
        )

        // Check if a number is prime
        func isPrime(n int) bool {
            if n <= 1 {
                return false
            }
            for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
                if n%i == 0 {
                    return false
                }
            }
            return true
        }

        // Generate the prime spiral
        func generatePrimeSpiral(size int) [][]int {
            // Initialize the 2D grid
            spiral := make([][]int, size)
            for i := range spiral {
                spiral[i] = make([]int, size)
            }

            // Directions to move in the spiral (right, down, left, up)
            directions := []struct{ dx, dy int }{
                {1, 0}, {0, 1}, {-1, 0}, {0, -1},
            }

            x, y, dir := size/2, size/2, 0
            num := 1
            spiral[x][y] = num

            for layer := 1; layer <= size/2; layer++ {
                for i := 0; i < 2*layer; i++ {
                    x += directions[dir].dx
                    y += directions[dir].dy
                    num++
                    spiral[x][y] = num
                }
                dir = (dir + 1) % 4
            }

            return spiral
        }

        // Print the spiral with prime numbers highlighted
        func printSpiral(spiral [][]int) {
            for _, row := range spiral {
                for _, val := range row {
                    if isPrime(val) {
                        fmt.Print("* ")
                    } else {
                        fmt.Print(". ")
                    }
                }
                fmt.Println()
            }
        }

        func main() {
            var size int
            fmt.Print("Enter the size of the spiral (odd number): ")
            fmt.Scan(&size)

            if size%2 == 0 {
                fmt.Println("Please enter an odd number for the spiral size.")
                os.Exit(1)
            }

            spiral := generatePrimeSpiral(size)
            printSpiral(spiral)
        }
        

Program Structure and Explanation

This Go program has three main components:

  • isPrime function: This function checks whether a given number is prime. It returns true if the number is prime, otherwise false.
  • generatePrimeSpiral function: This function generates a 2D grid of numbers arranged in a spiral pattern. It starts from the center and fills the grid in a clockwise direction.
  • printSpiral function: This function prints the spiral on the screen, highlighting prime numbers with a ‘*’ symbol and non-prime numbers with a ‘.’ symbol.

How the Program Works

1. The program first asks for the size of the spiral. It should be an odd number to ensure that the center of the spiral is well-defined.

2. It then calls the generatePrimeSpiral function to create the spiral grid.

3. Finally, it calls the printSpiral function to display the spiral, where prime numbers are marked with an asterisk (*) and non-prime numbers with a period (.)

How to Run the Program

  1. Ensure that you have Go installed on your system. You can download it from the official website here.
  2. Save the Go code in a file, for example prime_spiral.go.
  3. Open a terminal and navigate to the directory where the file is saved.
  4. Run the program by typing the command go run prime_spiral.go.
  5. Enter the desired size for the spiral (it should be an odd number). The program will display the prime spiral on the terminal.
© 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 :)