Skip to content

Instantly share code, notes, and snippets.

@quantumelixir
Created January 15, 2011 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantumelixir/780954 to your computer and use it in GitHub Desktop.
Save quantumelixir/780954 to your computer and use it in GitHub Desktop.
Print the ulam spiral
package main
import (
"os"
"fmt"
"flag"
"strconv"
)
func isPrime(n int) (bool) {
if n == 2 || n == 3 {
return true
}
if n == 1 || n % 2 == 0 || n % 3 == 0 {
return false
}
sqrt := 1
for sqrt*sqrt < n {
sqrt++
}
for j := 5; j <= sqrt; j += 6 {
if n%j == 0 || n%(j+2) == 0 {
return false
}
}
return true
}
func main() {
var size int
flag.Parse()
if flag.NArg() != 1 {
fmt.Println("specify one integer argument")
os.Exit(1)
} else {
size, _ = strconv.Atoi(flag.Arg(0))
}
grid := make([][]int, size)
for k := 0; k < size; k++ {
grid[k] = make([]int, size)
}
mid := (size - 1)/2
grid[mid][mid] = 1
x, y := mid, mid
step, count := 1, 2
dx, dy := 0, 1
for ; count <= size*size; step++ {
for k := 1; count <= size*size && k <= 2; k++ {
for i := 1; count <= size*size && i <= step; i++ {
x+=dx
y+=dy
grid[x][y] = count
count++
}
dx, dy = dy, dx
}
dx, dy = -dx, -dy
}
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
if isPrime(grid[i][j]) {
fmt.Printf("%d\t", grid[i][j])
} else {
fmt.Printf("\t")
}
}
fmt.Printf("\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment