Advertisement
hankieshahs

Sieve of Eratosthenes image generator python code

Nov 5th, 2013
610
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. #Made by /u/iamaquantumcomputer
  2. #Preview to what output should look like: http://imgur.com/gallery/0gI8eK6
  3. #usage from terminal: $ python sieve.py width height
  4. #   example used to generate linked preview: $ python sieve.py 683 384
  5. #relies on PIL (Python Imaging Library) to function
  6.  
  7. from PIL import Image
  8. import sys
  9.  
  10. try:
  11.     width = int(sys.argv[1])
  12.     height = int(sys.argv[2])
  13. except IndexError:
  14.     width = 1080
  15.     height = 768
  16. except ValueError:
  17.     width = 1080
  18.     height = 768
  19.  
  20. def convert(num):
  21.     x = (num-1)%width
  22.     y = (num-1)/width
  23.    
  24.     return (x,y)
  25.  
  26. def plot(num):
  27.     tup = convert(num)
  28.     x = tup[0]
  29.     y = tup[1]
  30.     pixdata[x,y] = (0,0,0)
  31.  
  32. def calcsieve():
  33.     plot(1)
  34.  
  35.     print "eliminating multiples of 2"
  36.     for m in range(4,width*height+1,2):
  37.         plot(m)
  38.         #print "\tkilling " + str(m)
  39.     for a in range(3,int((width*height)**.5)+1,1):
  40.         coor = convert(a)
  41.         if (pixdata[coor[0],coor[1]][0]==255):
  42.             print "eliminating multiples of " + str(a)
  43.             for b in range(3*a,width*height+1,2*a):
  44.                 #print "\tkilling " + str(b)
  45.                 plot(b)
  46.  
  47. img = Image.new("RGB", (width,height), (255,255,255))
  48. pixdata = img.load()
  49. calcsieve()
  50. img.save("sieve.png", "PNG")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement