Skip to content

Instantly share code, notes, and snippets.

@utgwkk
Created January 19, 2014 10:53
Show Gist options
  • Save utgwkk/8503228 to your computer and use it in GitHub Desktop.
Save utgwkk/8503228 to your computer and use it in GitHub Desktop.
Generate "Ulam spiral (prime spiral)"
# -*- encoding: utf-8 -*-
from PIL import Image
from math import sqrt
Max = 333
pix = 3
filename = 'output.png'
f1 = lambda x,y: sorted(range(x-(y-1)*2+1-y, x-(y-1)*2+1),reverse=True)
isprime = lambda x: x != 1 and (x == 2 or not 0 in [x%y for y in range(2,int(sqrt(x))+1)])
ulam = []
for i in range(Max/2+1):
ulam.append(f1((Max-2*i)**2,Max-2*i))
for i in range(1,Max/2+1):
ulam.append(range((i*2+1)**2-i*2,(i*2+1)**2+1))
for i in range(1,len(ulam)-1):
m = i if i < Max/2+1 else Max - i - 1
for j in range(m):
ulam[i].insert(j,ulam[i-1][j]+1)
ulam[i] += reversed([ulam[i-1][Max-1-x]-1 for x in range(m)])
for i in range(len(ulam)):
ulam[i] = map(isprime,ulam[i])
img = Image.new('RGB',(Max*pix,Max*pix),(255,255,255))
for y in range(len(ulam)):
for x in range(len(ulam[i])):
if ulam[y][x]: color = (0,0,0)
else: color = (255,255,255)
for a in range(pix):
for b in range(pix):
img.putpixel((x*pix+b,y*pix+a),color)
img.save(filename, 'PNG')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment