cplusplus
cplusplus

 

In this guide, we will walk through how to create a prime spiral (Ulam Spiral) in C++ programming. The Ulam Spiral is a visual representation of prime numbers arranged in a spiral pattern. This pattern highlights the distribution of prime numbers in a 2D grid.

Objective

The objective of this program is to generate an Ulam Spiral by plotting prime numbers in a spiral order on a grid. This exercise will help you understand how prime numbers behave in a spatial format and how they are distributed in a grid-like structure.

Prime Spiral Code in C++


#include 
#include 
#include 
using namespace std;

// Function to check if a number is prime
bool isPrime(int num) {
    if (num <= 1) return false;
    for (int i = 2; i <= sqrt(num); i++) {
        if (num % i == 0) return false;
    }
    return true;
}

// Function to generate and print the prime spiral
void generatePrimeSpiral(int size) {
    vector<vector> spiral(size, vector(size, 0));

    int x = size / 2, y = size / 2; // Start in the center of the grid
    int num = 2; // Starting number
    int direction = 0; // Direction: 0 -> Right, 1 -> Up, 2 -> Left, 3 -> Down
    int steps = 1;
    int count = 0;

    spiral[x][y] = 1; // Starting point is marked as prime (1)

    while (count < size * size) {
        for (int i = 0; i < steps; i++) {
            // Move in the current direction
            if (isPrime(num)) {
                spiral[x][y] = num;
            }
            num++;
            count++;

            // Change direction based on current direction
            if (direction == 0) y++; // Right
            else if (direction == 1) x--; // Up
            else if (direction == 2) y--; // Left
            else if (direction == 3) x++; // Down
        }

        // Change direction and increase step size after 2 directions
        direction = (direction + 1) % 4;
        if (direction % 2 == 0) steps++; // Increase steps after every two directions
    }

    // Print the spiral
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (spiral[i][j] == 0) cout << ". ";
            else cout << spiral[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int size;
    cout << "Enter the size of the prime spiral (odd number): "; cin >> size;

    // Ensure the size is odd
    if (size % 2 == 0) size++;

    generatePrimeSpiral(size);

    return 0;
}
        

Explanation of the Program

The program starts by defining a function isPrime that checks whether a given number is prime. We use this function to check each number in the spiral.

The generatePrimeSpiral function initializes a 2D grid of size size x size, with the starting point at the center of the grid. The algorithm fills the grid in a spiral pattern by moving in the following directions: right, up, left, and down. As it moves, it checks whether the current number is prime. If it is, the number is placed in the grid; otherwise, the program moves to the next number.

The spiral’s direction changes after every two moves, and the number of steps taken in each direction increases after each complete cycle of four moves.

Steps to Run the Program

  • Step 1: Save the code in a C++ source file, e.g., prime_spiral.cpp.
  • Step 2: Compile the program using a C++ compiler, e.g., g++ prime_spiral.cpp -o prime_spiral.
  • Step 3: Run the compiled program, e.g., ./prime_spiral.
  • Step 4: Enter the size of the prime spiral (an odd number). The program will then display the prime spiral on the console.
© 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 :)