Skip to content

Instantly share code, notes, and snippets.

@bgnori
Created December 28, 2011 01:15
Show Gist options
  • Save bgnori/1525696 to your computer and use it in GitHub Desktop.
Save bgnori/1525696 to your computer and use it in GitHub Desktop.
ウラムの螺旋
#!/usr/bin/python
# -*- coding utf8 -*-
def isPrime(n):
if n == 1:
return False
elif n == 2:
return True
else:
for i in range(2, n):
d, m = divmod(n, i)
if m == 0:
return False
return True
class Matrix(object):
def __init__(self, size, filter=None):
self.size = size
self.matrix = {}
self._filter = filter
def filter(self, n):
if self._filter:
return self._filter(n)
return n
def make(self, n=None, origin=None):
if n is None:
n = self.size
if origin is None:
origin = (0, 0)
print n, origin
assert n > 0
if n==1:
self.matrix[origin] = 1
return
d, isodd = divmod(n, 2)
if isodd:
for i in range(n):
self.matrix[(origin[0], origin[1]+i)] = self.filter(n*n - i)
for i in range(n-1):
self.matrix[(origin[0]+1+i, origin[1]+n-1)] = self.filter(n*n - n - i)
o2 = origin[0]+1, origin[1]
else:
for i in range(n):
self.matrix[(origin[0]+n-1, origin[1]+n-1-i)] = self.filter(n*n - i)
for i in range(n-1):
self.matrix[(origin[0]+n-2-i, origin[1])] = self.filter(n*n - n - i)
o2 = origin[0], origin[1] + 1
self.make(n-1, o2)
def print_matrix(self):
for j in range(self.size):
line = []
for i in range(self.size):
line.append('%3i'%(self.matrix[(i, j)],))
print '|'.join(line)
m = Matrix(6)
m.make()
m.print_matrix()
print isPrime(7)
print isPrime(17)
print isPrime(29)
print isPrime(169)
m = Matrix(11, isPrime)
m.make()
m.print_matrix()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment