<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Problematic Sets</title>
	<atom:link href="http://problematicsets.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://problematicsets.com</link>
	<description>Learning to solve problems, one blog post at a time</description>
	<lastBuildDate>Fri, 18 May 2012 19:17:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Project Euler 120: Finding a maximum remainder</title>
		<link>http://problematicsets.com/project-euler-120-finding-a-maximum-remainder/</link>
		<comments>http://problematicsets.com/project-euler-120-finding-a-maximum-remainder/#comments</comments>
		<pubDate>Fri, 18 May 2012 19:15:33 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=968</guid>
		<description><![CDATA[Dreamshire and KeyZero Conversation both have good discussions about this problem. I wrote a bunch of code, mostly around polynomial expansions and summations, to see what these sequences look like when you expand them for larger and larger n. #euler 120 #let's use our own multiplication of polynomial function def poly(a, b): #takes as input [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://www.google.com/url?sa=t&#038;rct=j&#038;q=&#038;esrc=s&#038;source=web&#038;cd=1&#038;ved=0CFcQFjAA&#038;url=http%3A%2F%2Fblog.dreamshire.com%2F2012%2F04%2F26%2Fproject-euler-problem-120-solution%2F&#038;ei=3p-2T9XnN4X56QGEuJTqCg&#038;usg=AFQjCNFEs3mTAGikn-3khogxGvdP11I2zA">Dreamshire</a> and <a href="http://keyzero.wordpress.com/2010/05/03/project-euler-problem-120/">KeyZero Conversation</a> both have good discussions about this <a href="http://projecteuler.net/problem=120">problem</a>.</p>
<p>I wrote a bunch of code, mostly around polynomial expansions and summations, to see what these sequences look like when you expand them for larger and larger n.</p>
<pre>
#euler 120

#let's use our own multiplication of polynomial function

def poly(a, b):  #takes as input polynomial a and b, and multiplies them
    la = len(a)
    lb = len(b)
    orderA = la - 1
    orderB = lb - 1
    outputOrder = orderA + orderB
    numCoefficients = outputOrder + 1 # i.e. a fifth order polynomial has 6 coeff.
    output = [0 for x in range(numCoefficients)]
    for i in range(la):    # loop of loops to multiply coefficients and sum them up
        coefA = a[i]
        tempOrderA = la - 1 - i
        for j in range(lb):
            coefB = b[j]
            tempOrderB = lb - 1 - j
            orderProduct = tempOrderA + tempOrderB
            coefProduct = coefA * coefB
            outputIndex = len(output) - 1 - orderProduct
            output[outputIndex] += coefProduct
    return output

def pToTheN(polynomial, n):   #polynomial raised to the nth power
    tempList = [polynomial for x in range(n)]
    return reduce(poly, tempList)

def polySum(a, b):  #sum up two polynomials, can be of different order
    # first, normalize a and b to be polynomials of same length (the longer length)
    # insert leading zeroes into the smaller length polynomial
    la = len(a)
    lb = len(b)
    outputOrder = max(la, lb)
    diffA, diffB = 0, 0
    if la < outputOrder:
        diffA = outputOrder - la
    if lb < outputOrder:
        diffB = outputOrder - lb
    tempA = []
    tempB = []
    while diffA > 0:
        tempA.append(0)
        diffA -= 1
    while diffB > 0:
        tempB.append(0)
        diffB -= 1
    for i in a:
        tempA.append(i)
    for i in b:
        tempB.append(i)
    output = [0 for i in range(outputOrder)]
    for j in range(outputOrder):
        output[j] = tempA[j] + tempB[j]
    return output

# Dreamshire's analysis of this problem enumerated the expansion of these polynomial sequences
# let's recreate the expansion....
# let's generate the sequence for n from 1 to 10 of (a-1)^n + (a+1)^n

aMinus = [1, -1]
aPlus = [1, 1]

for n in range(1,11):
    first = pToTheN(aMinus, n)
    second = pToTheN(aPlus, n)
    print n, polySum(first, second)

# Notice, per Dreamshire, that for any even value of n, the remainder is always 2
# for odd values of n, the remainder will be 2an mod a^2
# so the maximum remainder is with an odd n, and will be 2an mod a^2

# maximizing the remainder occrus when n = (a-1)/2
# rmax quals 2 * a * ((a-1)/2)

answer = 0
for a in range(3, 1001):
    rmax = 2 * a * ((a-1)/2)
    answer += rmax

print answer
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/project-euler-120-finding-a-maximum-remainder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler 121: Investigating a game of chance</title>
		<link>http://problematicsets.com/project-euler-121-investigating-a-game-of-chance/</link>
		<comments>http://problematicsets.com/project-euler-121-investigating-a-game-of-chance/#comments</comments>
		<pubDate>Thu, 17 May 2012 19:09:21 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=965</guid>
		<description><![CDATA[Project Euler 121 Dreamshire has a good blog post analyzing this problem and how to get the solution. I decided to write my own function that multiplies polynomials, though I&#8217;m sure there&#8217;s a library somewhere that already has it done. Fun problem! #euler 121 # from Dreamshire blog, we know this can be solved through [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://projecteuler.net/problem=121">Project Euler 121</a></p>
<p><a href="http://blog.dreamshire.com/2009/05/25/project-euler-problem-121-solution/">Dreamshire</a> has a good blog post analyzing this problem and how to get the solution.</p>
<p>I decided to write my own function that multiplies polynomials, though I&#8217;m sure there&#8217;s a library somewhere that already has it done.</p>
<p>Fun problem!</p>
<pre>
#euler 121

# from Dreamshire blog, we know this can be solved through the use of an
# ordinary generating function

#let's write our own multiplication of polynomial function

# takes as input polynomial a and b
# where coefficients are of the form  ax^n +bx^(n-1) + cx^(n-2) + .... +
# so polynomial x^3 + 5x^2 + 8x - 14 is represented as a list
# [1, 5, 8, -14]
# we know this is a third order polynomial from the length of the list and we
# know the coefficients

# so (x+1) * (x+2)
# we know is x^2 + 3x  +2
# so our function would take poly([1,1],[1,2]) and return [1,3,2]

# we know from the length of the polynomials, what the order of the output should be
# i.e. a third order polynomial * 2nd order polynomial gives us a fifth order poly
# 

def poly(a, b):  #takes as input polynomial a and b
    la = len(a)
    lb = len(b)
    orderA = la - 1
    orderB = lb - 1
    outputOrder = orderA + orderB
    numCoefficients = outputOrder + 1 # i.e. a fifth order polynomial has 6 coeff.
    output = [0 for x in range(numCoefficients)]
    for i in range(la):    # loop of loops to multiply coefficients and sum them up
        coefA = a[i]
        tempOrderA = la - 1 - i
        for j in range(lb):
            coefB = b[j]
            tempOrderB = lb - 1 - j
            orderProduct = tempOrderA + tempOrderB
            coefProduct = coefA * coefB
            outputIndex = len(output) - 1 - orderProduct
            output[outputIndex] += coefProduct
    return output

# n =15, so we want a sequence (x+1), (x+2), (x+3) .... and so forth to (x+15)
# our poly function represents these polynomials as their coefficients, e.g. (1,1) , (1,2), (1,3)

trials = 15

f = [(1,i) for i in range(1, trials+1)]
print f

# let's use python reduce to generate the product of all these polynomials

g = reduce(poly, f)
print g

# now we need to some up the coefficients for the first 8 terms of this sequence
s = sum([g[i] for i in range(8)])
print s

# take this sum, and divide it by (n+1)!, or 16!

def fact(n):
    return reduce(lambda x,y: x*y, range(1, n+1))

d = fact(16)
print d

prizeFund = d/s
print "the answer is ", prizeFund
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/project-euler-121-investigating-a-game-of-chance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler 108: Solving a Diophantine Equation</title>
		<link>http://problematicsets.com/project-euler-108-solving-a-diophantine-equation/</link>
		<comments>http://problematicsets.com/project-euler-108-solving-a-diophantine-equation/#comments</comments>
		<pubDate>Wed, 16 May 2012 13:23:03 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=958</guid>
		<description><![CDATA[I found two good blog articles on how to approach Project Euler 108: KeyZero Conversation: Comments on Computing Free Lancers Unite Here&#8217;s my python code. It takes around 50 seconds. #Euler 108 #KeyZero Conversation approach #1/x + 1/y = 1/n #using algebra, we solve for y in terms of x and n # y = [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I found two good blog articles on how to approach <a href="http://projecteuler.net/problem=108">Project Euler 108</a>:</p>
<p><a href="http://keyzero.wordpress.com/2010/06/05/project-euler-problem-108/">KeyZero Conversation: Comments on Computing</a><br />
<a href="http://freelancersunite.net/project_euler/project-euler-problem-108-110/">Free Lancers Unite</a></p>
<p>Here&#8217;s my python code.   It takes around 50 seconds.</p>
<pre>

#Euler 108

#KeyZero Conversation approach

#1/x + 1/y = 1/n
#using algebra, we solve for y in terms of x and n
# y = nx/(x-n)
# let d = (x-n)
# y = nx/d
# x = d+n
# y = n(d+n) / d
# y = (nd + n^2)/d
# y = n + n^2/d
# so for y to be integer, we need to find divisors d of n^2
# then backsubstitute
# x, y (with the constraints that n < x <= 2n)

# number of solutions for n is (divisors(n^2)+1)/2

# number of divisors of an integer are product of powers of prime factor + 1.
# i.e. 24 is 2^3 * 3^1. The powers are 3 and 1.  The product of (3+1) and (1+1)
# is 8, so there are eight divisors.

# reduce the search space.  We want to find any value n where n^2 has at least
# 2000 divisors.

# assume that it is made up of squares of small prime numbers
# 2^2 * 3^2 * 5^2 *7^2 *11^2 * 13^2  (this is six different factors all raised to the
# power of 2).  Also, this is (2*3*5*7*11*13)^2, or 30030^2.
# So number of divisors is (2+1)^6, or 729.  This is too low, but we can start here

# If we go to 7 different factors, we get to
# (2*3*5*7*11*13*17)^2, or 510510^2.
# Number of divisors is (2+1)^7, or 2187.  This is greater than 2000, so this could be it.

import math
import operator
import time
t0 = time.time()

#generate sieve

import math

def sieve(n):
    initSieve = []
    maxNum = int(math.sqrt(n))+1
    for i in range(2,n):
        initSieve.append(True)
    j = 2
    while j <= maxNum:
        if initSieve[j-2]:
            for k in range(j*j, n, j):
                initSieve[k-2] = False
        j += 1
    outputList = [x+2 for x in range(len(initSieve)) if initSieve[x]]
    return outputList

topSieve = 50
primes = sieve(topSieve)  #prime factors less than

print primes
lenP = len(primes)   #length of primes
print lenP

def divisors(n, primes):   # factorizes a number using small primes
    tempN = n
    t = [0 for x in range(len(primes))]
    idx = 0
    while idx < len(t):
        while tempN > 1 and tempN % primes[idx] == 0:
            t[idx] += 1
            tempN /= primes[idx]
        if tempN == 1:
            return True, t, tempN
        idx += 1
    return False, t, tempN

# our divisors function takes a number n,
# sees if we can factorize it using prime numbers within our sieve
# so within our search space - we will take a number n, try to factorize it,
# only using these prime factors.
# if the number can be factorized using these prime factors, then we get a True

def sumDiv(takesList):   # takes our factorization list, returns number of divisors
    c = 1
    for i in takesList:
        if i > 0:
            c *= (i+1)
    return c

# this is the product of the first 6 primes
start = 2 * 3 * 5 * 7 * 11 * 13
# another way to get this is
s2 = reduce(operator.mul, [primes[x] for x in range(6)])

incr = s2

testNum = start

def isSquare(possibleAnswer):  #takes as input list of exponents
    f = [int(math.pow(primes[i], possibleAnswer[i])) for i in range(lenP)]
    test = reduce(operator.mul, f)
    r = int(math.sqrt(test))
    if r*r == test:
        return True, test, r
    else:
        return False, test, r

while True:
    a, b, c = divisors(testNum, primes)
    if a:   #this should always be true, since we're incrementing by s2
        d = sumDiv(b)
        if d > 2000:
            e, f, g = isSquare(b)
            if e:
                print a, b, c
                print f, g
                print "the answer n is", g
                break
    testNum += incr

t1 = time.time()
print t1 - t0, "seconds"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/project-euler-108-solving-a-diophantine-equation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cool list of books for self-study</title>
		<link>http://problematicsets.com/cool-list-of-books-for-self-study/</link>
		<comments>http://problematicsets.com/cool-list-of-books-for-self-study/#comments</comments>
		<pubDate>Mon, 14 May 2012 22:03:55 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Notes]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=956</guid>
		<description><![CDATA[Dan over at the blog A Broader View has a cool list of books for self study on math, computer science and economics.]]></description>
			<content:encoded><![CDATA[<p></p><p>Dan over at the blog A Broader View has a <a href="http://breadthfirst.wordpress.com/2009/11/10/math-computer-science-and-economics-books-for-self-study/">cool list of books for self study</a> on math, computer science and economics.</p>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/cool-list-of-books-for-self-study/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler 90: An unexpected way of combining two dice to make a perfect square</title>
		<link>http://problematicsets.com/project-euler-90-an-unexpected-way-of-combining-two-dice-to-make-a-perfect-square/</link>
		<comments>http://problematicsets.com/project-euler-90-an-unexpected-way-of-combining-two-dice-to-make-a-perfect-square/#comments</comments>
		<pubDate>Fri, 11 May 2012 17:03:58 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=954</guid>
		<description><![CDATA[My solution to Project Euler 90: # euler 90 import itertools x = [x for x in itertools.combinations('0123456789',6)] y = itertools.combinations(x, 2) #iterable of 2 distinct dice squares = ['01','04','09','16','25','36','49','64','81'] #keep as strings def addReverseDigit(takesList): if '6' in takesList and '9' in takesList: return takesList elif '6' in takesList: takesList.append('9') return takesList elif '9' in [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>My solution to <a href="http://projecteuler.net/problem=90">Project Euler 90</a>:</p>
<pre>
# euler 90

import itertools

x = [x for x in itertools.combinations('0123456789',6)]
y = itertools.combinations(x, 2)  #iterable of 2 distinct dice

squares = ['01','04','09','16','25','36','49','64','81']  #keep as strings

def addReverseDigit(takesList):
    if '6' in takesList and '9' in takesList:
        return takesList
    elif '6' in takesList:
        takesList.append('9')
        return takesList
    elif '9' in takesList:
        takesList.append('6')
        return takesList
    else:
        return takesList

def genNums(c1, c2):  #takes die1 and die2
    test = {}  # test is an array of all perfect squares, set to False
    for i in squares:
        test[i] = False
    cL1 = addReverseDigit(list(c1))  #convert tuple to list, then add reverse digit
    cL2 = addReverseDigit(list(c2))
    for i in cL1:
        for j in cL2:
            ij = i+j  #concatenating strings
            if ij in test:
                test[ij] = True
            ji = j+i
            if ji in test:
                test[ji] = True
    assume = True
    for k, v in test.items():
        if v == False:
            assume = False
    return assume

answer = 0

for a in y:
    if genNums(a[0],a[1]):
        answer += 1

print answer
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/project-euler-90-an-unexpected-way-of-combining-two-dice-to-make-a-perfect-square/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler 93: Using four distinct digits and the rules of arithmetic, find the longest sequence of target numbers.</title>
		<link>http://problematicsets.com/project-euler-93-using-four-distinct-digits-and-the-rules-of-arithmetic-find-the-longest-sequence-of-target-numbers/</link>
		<comments>http://problematicsets.com/project-euler-93-using-four-distinct-digits-and-the-rules-of-arithmetic-find-the-longest-sequence-of-target-numbers/#comments</comments>
		<pubDate>Fri, 11 May 2012 14:14:44 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=949</guid>
		<description><![CDATA[I finished Project Euler 93 this morning. I enjoyed reading Kristian&#8217;s blueprint to the problem at Mathblog, and I emulated his approach in generating all the brute force combinations of digits a]]></description>
			<content:encoded><![CDATA[<p></p><p>I finished <a href="http://www.mathblog.dk/project-euler-93-longest-sequence/">Project Euler 93</a> this morning.  </p>
<p>
I enjoyed reading Kristian&#8217;s blueprint to the problem at Mathblog, and I emulated his approach in generating all the brute force combinations of digits a<b<c<d, then generating all possible permutations of those 4-digit combinations, then generating all the possible tuples of operators e.g. (+,-,*), and then generating the scenarios to insert parentheses into the proper locations.</p>
<p>Rather then writing code for the mathematical operators +,-,*,/ and figuring out how to write the priority of mathematical operators (i.e. scan from left to right, do operators within parentheses first, and do *,/ before doing +,-), I ended up mostly doing string operations and then sending the resulting string directly to the Python operator using the eval() function.</p>
<p>You have to be careful of the DIV/#0 error, so you have to write an exception handler for that error.</p>
<p>Also, you have to be careful because in python, all of the numbers are initially handled as integers, so when dividing, i.e. 4/3, Python will give you the result 1.   So when dealing with division, you have to convert the numbers to float first, to get Python to return 4/3 = 1.3333.</p>
<p>Finally - we keep track of the maximum N and the combination that yields that maximum N.</p>
<p>Solution took 100 seconds, so it did violate the 1 minute rule for Project Euler.  Oh well!</p>
<pre>
# euler 93
import time
t0 = time.time()

import itertools

temp = itertools.combinations(&#8217;0123456789&#8242;,4)
c = []
for i in temp:
    j = [x for x in i]
    c.append(j)

op = [i for i in itertools.product('+-*/',repeat=3)]

def calc(c, op):
    temp = c[0] + op[0] + c[1] + op[1] + c[2] + op[2] + c[3]
    return temp

## use string operations to insert parentheses

def insParenth(s):  #takes a+b+c+d
    a = s[:]
    b = s[:2] + &#8216;(&#8216; + s[2:5] + &#8216;)&#8217; + s[5:]  # a + (b+c) + d
    c = s[:4] + &#8216;(&#8216; + s[4:7] + &#8216;)&#8217; # a+b+(c+d)
    d = s[:2] + &#8216;(&#8216; + s[2:7] + &#8216;)&#8217;   # a+(b+c+d)
    e = &#8216;(&#8216; + s[:3] + &#8216;)&#8217; + s[3] + &#8216;(&#8216; + s[4:7] + &#8216;)&#8217;  #(a+b)+(c+d)
    return [a,b,c,d,e]

def convToFloat(st):  #if there is a divide operation, we need to convert to floating
    if &#8216;/&#8217; in st:
        output = &#8221;
        for i in st:
            if i in &#8217;0123456789&#8242;:
                output += &#8216;float(&#8216; + i + &#8216;)&#8217;
            else:
                output += i
        return output
    else:
        return st

def evalP(par):
    output = []
    for a in par:
        try:
            output.append(eval(a))
        except ZeroDivisionError:
            output.append(None)
    return output

largestSoFar = 0

for i in c:  #unique combinations of a<b<c<d
    test = set()
    for j in itertools.permutations(i):  #all permuations of c
        for tempOp in op:   # all operations
            tempCase = calc(j, tempOp)
            tcp = insParenth(tempCase)
            tcp = [convToFloat(x) for x in tcp]
            outp = evalP(tcp)
            for k in outp:
                if type(k) == int and k >= 1:
                    test.add(k)
                elif type(k) == float:
                    if int(k) !=0:
                        if k % int(k) == 0 and k >= 1:
                            test.add(int(k))
##    print i, test
    startNum = 1
    while startNum in test:
        startNum += 1
##    print &#8220;the first number not in the set is &#8220;, startNum
    mn = startNum &#8211; 1
##    print &#8220;the max number is &#8220;, mn
    if mn > largestSoFar:
        largestSoFar = mn
        answer = i
        print &#8220;the largest N so far is &#8220;, largestSoFar
        print &#8220;the answer so far is &#8220;, answer
        print &#8220;&#8221;

t1 = time.time()
print t1-t0, &#8220;seconds&#8221;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/project-euler-93-using-four-distinct-digits-and-the-rules-of-arithmetic-find-the-longest-sequence-of-target-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler 94: Investigating almost equilateral triangles with integral sides and area.</title>
		<link>http://problematicsets.com/project-euler-94-investigating-almost-equilateral-triangles-with-integral-sides-and-area/</link>
		<comments>http://problematicsets.com/project-euler-94-investigating-almost-equilateral-triangles-with-integral-sides-and-area/#comments</comments>
		<pubDate>Mon, 07 May 2012 16:40:24 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=947</guid>
		<description><![CDATA[Thanks for Kristian and Mathblog for a clear articulation of the trick to solving this problem. Surprise &#8211; it&#8217;s a Pell equation. I implemented the solution in my own hacky fashion, reusing some old code I wrote for Project Euler 66, and following Kristian&#8217;s blueprint. #euler 94 #first solve the pell equation: X^2 - 3*Y^2 [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Thanks for<a href="http://www.mathblog.dk/project-euler-94-almost-equilateral-triangles/"> Kristian and Mathblog</a> for a clear articulation of the trick to solving this problem.  Surprise &#8211; it&#8217;s a Pell equation.</p>
<p>I implemented the solution in my own hacky fashion, reusing some old code I wrote for Project Euler 66, and following Kristian&#8217;s blueprint.</p>
<pre>
#euler 94

#first solve the pell equation:  X^2 - 3*Y^2 = 1 ; thanks to MathBlog

# we coded up an earlier solution to Project Euler 66 we can reuse

import math

# x2 - Ny2 = 1
# no solutions when D is square

#brahmagupta created chakravala method
# identity
# (a2 - Nb2)(c2 - Nd2) = (ac+Nbd)2 - N(ad+bc)2
# first compose triplets
# (x,y,k) with trivial triple (m, 1, m2-N)
# to get triplet( (am + Nb, a+bm, k(m2-N) )
# then scale down by k

def reduceTriplet(triplet, n):
    a = triplet[0]
    b = triplet[1]
    k = triplet[2]
    mStart = 1
    while True:
        if (a + b*mStart) % k == 0:
            break
        mStart += 1
##    print mStart
    m = mStart
    step1 = int(math.fabs(k))
    least = int(math.fabs(m*m - n))
    while True:
        mNew = m + step1
        if int(math.fabs(mNew * mNew - n )) > least:
            break
        else:
            m =  mNew
            least = int(math.fabs(m*m - n))
##    print m
    newA = (a*m + n*b)/ int(math.fabs(k))
    newB = (a + b*m) / int(math.fabs(k))
    newK = (m*m-n) / k
##    print newA, newB, newK
    return (newA, newB, newK)

def chakra(n):   #takes integer, n can't be a perfect square
    root = int(math.sqrt(n))
    if root * root == n:
        raise ValueError
    # find an arbitary triplet (a, b, k), where b is 1
    r1 = root
    r2 = root + 1
    diff1 = r1 * r1 - n
    diff2 = r2 * r2 - n
    if math.fabs(diff1) < math.fabs(diff2):
        a = r1
    else:
        a = r2
    b = 1
    k = a*a - n
    triplet = (a, b, k)
##    print triplet
    # now compose this first triplet with (m, 1, m2-N)
    # select m so that (a+bm)/k is an integer, and that minimizes (m2-N)/k
    if triplet[2] == 1:
        return triplet
    result = reduceTriplet(triplet, n)
    while result[2] != 1:
        result = reduceTriplet(result, n)
    return result

# so fundamental solution to our pell equation is simply
print "The fundamental solution is "
print chakra(3)
print ""

# that was a lot of work to find the fundamental solution (2, 1, 1)!

# next use the recurrence relationship
# this class is a generator that creates the next integer solution of the
# pell equation x2 - 3y2 = 1

class pellRecur:
    def __init__(self):
        self.x = 2
        self.y = 1
        self.x1 = 2
        self.y1 = 1
        self.n = 3
    def next(self):
        tempX = self.x1 * self.x + self.n * self.y1 * self.y
        tempY = self.x1 * self.y + self.y1 * self.x
        self.x, self.y = tempX, tempY
    def __iter__(self):
        return self

# once we solve for the x, y in the pell equation
# we can check to see if a is an integer

def checkA1(pellSolution):  #takes a solution of our Pell Recurrence, i.e. (2,1)
    x = pellSolution[0]
    y = pellSolution[1]
    #case 1 : b= a+1, then a = 2x+1 / 3
    a1 = 2*x + 1
    if a1 % 3 == 0:
        side1 = a1/3
        base= side1 + 1
        area = base * y / 2
        baseInt = base*y % 2 == 0
        return True, side1, base, area, baseInt
    else:
        return False,

def checkA2(pellSolution):  #takes a solution of our Pell Recurrence, i.e. (2,1)
    x = pellSolution[0]
    y = pellSolution[1]
    #case 2 : b= a-1, then a = 2x-1 / 3
    a1 = 2*x - 1
    if a1 % 3 == 0:
        side1 = a1/3
        base = side1 - 1
        area = base * y / 2
        baseInt = base*y % 2 == 0
        return True, side1, base, area, baseInt
    else:
        return False,

# run our test to find all solutions to Pell equation
# we need to stop when perimeter is greater than 1 billion

p = pellRecur()
keepGoing = True
answers = []
while keepGoing:
    perim = (2 * p.x -1)  #this is simply 3 times the smaller side
    answers.append((p.x, p.y))
    if perim > 1000000000:
        keepGoing = False
    p.next()

#answers is a list of all solutions to pell, but we need to pop the last tuple

answers.pop()
#we also need to get rid of first tuple, because it is triangle with side (1,1,0),
# so it has area of zero
answers.pop(0)

# this loop goes through our Pell solutions, checks to see if a is integral length

sumPerims = 0
for t in answers:
    print t
    ta1, ta2 = checkA1(t), checkA2(t)
    print ta1, ta2
    if ta1[0]:
        sumPerims += 2*ta1[1] + ta1[2]
    if ta2[0]:
        sumPerims += 2*ta2[1] + ta2[2]

print sumPerims
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/project-euler-94-investigating-almost-equilateral-triangles-with-integral-sides-and-area/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes: Linked Lists chapter</title>
		<link>http://problematicsets.com/notes-linked-lists-chapter/</link>
		<comments>http://problematicsets.com/notes-linked-lists-chapter/#comments</comments>
		<pubDate>Mon, 16 Apr 2012 13:43:56 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Notes]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=943</guid>
		<description><![CDATA[http://greenteapress.com/thinkpython/html/chap17.html]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://greenteapress.com/thinkpython/html/chap17.html">http://greenteapress.com/thinkpython/html/chap17.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/notes-linked-lists-chapter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes: Master Method</title>
		<link>http://problematicsets.com/notes-master-method/</link>
		<comments>http://problematicsets.com/notes-master-method/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 18:30:44 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=938</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://problematicsets.com/wp-content/uploads/2012/04/mastermethod.jpg"><img src="http://problematicsets.com/wp-content/uploads/2012/04/mastermethod-300x129.jpg" alt="" title="mastermethod" width="300" height="129" class="alignleft size-medium wp-image-939" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/notes-master-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Algorithms &#8211; The minimal cut problem in graph partitioning</title>
		<link>http://problematicsets.com/algorithms-the-minimal-cut-problem-in-graph-partitioning/</link>
		<comments>http://problematicsets.com/algorithms-the-minimal-cut-problem-in-graph-partitioning/#comments</comments>
		<pubDate>Wed, 04 Apr 2012 19:52:08 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://problematicsets.com/?p=935</guid>
		<description><![CDATA[Another great lecture online from Stanford&#8217;s class on algorithms. This week&#8217;s programming challenge was solving the minimal cut problem. We reviewed different data structures used to capture the properties of graphs (which include the vertices and the edges that connect them). The problem is that you are given a list of nodes in a connected [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Another great lecture online from Stanford&#8217;s class on algorithms.</p>
<p>This week&#8217;s programming challenge was solving the minimal cut problem.  We reviewed different data structures used to capture the properties of graphs (which include the vertices and the edges that connect them).  </p>
<p>The problem is that you are given a list of nodes in a connected graph.  How do you partition the graph (divide it into two groups of connecting nodes), to minimize the number of cuts (or connections) that go across the two partitions?</p>
<p>This algorithm forces you to write a couple of subroutines &#8211; including how to use randomization in your algorithm to randomly select an edge in the graph to &#8220;contract&#8221; the graph around the two vertices that are at the endpoints of that randomly selected edge.</p>
<p>We&#8217;re mostly using adjacency lists to represent these data graphs, rather than adjacency matrices.</p>
<p>I used Python to code my solution.</p>
<p>While I won&#8217;t share the entire solution here, out of respect to the Stanford honor code, here&#8217;s a cool Python snippet that I used to randomly select an edge from the graph.  I built a class object for the graph, where self.G is a dictionary that has as primary keys the vertex in the graph, and where the entry in the dictionary for that key is the list of adjacent vertices.  This randomization snippet is pretty neat.   It takes that dictionary G, runs a double for loop to create an iterable list of all the possible edges in the graph, and then the python random.choice function randomly selects one of those edges.   The rest of the solution then takes that randomly selected edge, merges the vertices represented by the two endpoints, updates G to remove the two vertices, updates G to include a new vertex that represents the combined vertices, updates a new dictionary to keep track of all the combination steps we are taking, then a for loop to run this randomized algorithm a certain number of times (n squared log n) and find the minimal cut &#8230;. anyways &#8211; this was a super fun problem.   :</p>
<pre>
def chooseEdge(self):
        temp = [(a,b) for a in self.G for b in self.G[a]]
        return random.choice(temp)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://problematicsets.com/algorithms-the-minimal-cut-problem-in-graph-partitioning/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

