How to resolve the algorithm Ulam spiral (for primes) step by step in the Kotlin programming language

Published on 22 June 2024 08:30 PM

How to resolve the algorithm Ulam spiral (for primes) step by step in the Kotlin programming language

Table of Contents

Problem Statement

An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   starting at   1. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). Normally, the spiral starts in the "center",   and the   2nd   number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the   2nd   number)   is viewed upwards from the   1st   number instead of to the right, but that is just a matter of orientation. Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). [A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals   (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. Then, in the next phase in the transformation of the Ulam prime spiral,   the non-primes are translated to blanks. In the orange grid below,   the primes are left intact,   and all non-primes are changed to blanks.
Then, in the final transformation of the Ulam spiral (the yellow grid),   translate the primes to a glyph such as a   •   or some other suitable glyph.

The Ulam spiral becomes more visually obvious as the grid increases in size.

For any sized   N × N   grid,   construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number   (the default would be 1),   with some suitably   dotty   (glyph) representation to indicate primes,   and the absence of dots to indicate non-primes.
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Ulam spiral (for primes) step by step in the Kotlin programming language

Ulam Spiral Generator in Kotlin

This Kotlin code generates an Ulam spiral, which is a square grid of prime numbers arranged in a clockwise spiral pattern.

Object Definition:

  • The code is encapsulated in an object named Ulam.

Function generate():

  • generate() is the main function used to generate the Ulam spiral.
  • It takes three parameters:
    • n: The size of the grid (an integer greater than 1).
    • i: The starting number for the spiral (default is 1).
    • c: The character to use to represent prime numbers (default is '*').

Algorithm:

  • It starts with a 2D array s initialized with empty strings.
  • dir is an enum representing the direction of the spiral traversal (initially to the right).
  • y and x represent the current position in the grid.
    • x is shifted left by 1 for even n values to center the spiral.
  • The function iterates from i to n * n - 1 + i.
  • Inside the loop:
    • If the current cell s[y][x] is not empty, move to the next unfilled cell in the current direction.
    • If the current number j is prime, mark it in the grid using c.
    • Update the direction based on the current position and the state of adjacent cells.
    • Move one step in the updated direction.
  • After generating the spiral, it prints each row as a bracket-enclosed string.

Auxiliary Functions:

  • isPrime(): Checks if a given integer a is prime.
    • It uses a simple primality check algorithm.
  • Direction: An enum representing the four directions (RIGHT, UP, LEFT, DOWN).

Usage in main() Function:

  • main() calls the generate() function twice:
    • Once with c='0' to print the spiral with numbers instead of characters.
    • Once with the default character '*'.

Source code in the kotlin programming language

object Ulam {
    fun generate(n: Int, i: Int = 1, c: Char = '*') {
        require(n > 1)
        val s = Array(n) { Array(n, { "" }) }
        var dir = Direction.RIGHT
        var y = n / 2
        var x = if (n % 2 == 0) y - 1 else y // shift left for even n's
        for (j in i..n * n - 1 + i) {
            s[y][x] = if (isPrime(j)) if (c.isDigit()) "%4d".format(j) else "  $c " else " ---"

            when (dir) {
                Direction.RIGHT -> if (x <= n - 1 && s[y - 1][x].none() && j > i) dir = Direction.UP
                Direction.UP -> if (s[y][x - 1].none()) dir = Direction.LEFT
                Direction.LEFT -> if (x == 0 || s[y + 1][x].none()) dir = Direction.DOWN
                Direction.DOWN -> if (s[y][x + 1].none()) dir = Direction.RIGHT
            }

            when (dir) {
                Direction.RIGHT -> x++
                Direction.UP -> y--
                Direction.LEFT -> x--
                Direction.DOWN -> y++
            }
        }
        for (row in s) println("[" + row.joinToString("") + ']')
        println()
    }

    private enum class Direction { RIGHT, UP, LEFT, DOWN }

    private fun isPrime(a: Int): Boolean {
        when {
            a == 2 -> return true
            a <= 1 || a % 2 == 0 -> return false
            else -> {
                val max = Math.sqrt(a.toDouble()).toInt()
                for (n in 3..max step 2)
                    if (a % n == 0) return false
                return true
            }
        }
    }
}

fun main(args: Array<String>) {
    Ulam.generate(9, c = '0')
    Ulam.generate(9)
}


  

You may also check:How to resolve the algorithm Identity matrix step by step in the Ada programming language
You may also check:How to resolve the algorithm Bulls and cows step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Summarize primes step by step in the C programming language
You may also check:How to resolve the algorithm Jaro similarity step by step in the F# programming language
You may also check:How to resolve the algorithm Walk a directory/Non-recursively step by step in the Pike programming language