Thanks to everyone who submitted entries to this coding challenge. Amazingly, even though the challenge was open to all languages, every entry was in Python. I was also amazed to see how consistent most answers were in their methods – perhaps that’s what I get for proposing a challenge that included prime-checking and simple math, or perhaps you are all just good programmers and gravitate towards nice, clean, direct code.
Anyway, I chose Eric’s entry as the winner because he provided code that was easy to read, answered the problem elegantly AND also supplied documentation that made it easy to follow the method he was taking.
—Please note that I have changed the winner for this competition. I initially mis-attributed Eric’s work to another entrant. To rectify this, both Eric and Russel (whose solution was also very good and similar in approach, but not printed below) have been awarded the prize. —
Here’s his code. Copy and paste it into your favorite method of running python programs (I stick to codecademy labs for the most part because I haven’t figured out how to run python reliably anywhere else). Russel has won a free copy of my zombie fractions book, ‘In Parts’ which he can donate to the fraction- and zombie- loving person in his life.
-
# Goldbach’s Conjecture
-
# Eric
-
from math import sqrt,ceil
-
max = 400
-
def primeSieve(max):
-
“””Lists primes upto ~10,000,000 fairly quickly”””
-
quickList = [True for i in range (max-1)]
-
# highest possible prime
-
maxCheck = ceil(sqrt(max))
-
i = 2
-
while i != maxCheck:
-
# if i is prime
-
if quickList[i-2] == True:
-
# k keeps track of looper
-
k = i
-
while i + k <= max:
-
quickList[i+k-2] = False
-
k += i
-
i += 1
-
else:
-
i += 1
-
primeList = [iNum+2 for iNum,i in enumerate(quickList) if i == True]
-
return primeList
-
primes = primeSieve(max)
-
# list of even numbers from 4 – max
-
evens = [2*i+4 for i in range((max-2)/2)]
-
# cycle through combinations of sums of primes, record what works
-
sums = []
-
def expressAsSum(target):
-
for i in primes:
-
for j in primes:
-
if i+j == target:
-
sums.append(i)
-
sums.append(j)
-
return True
-
# if no solutions are found, we’ve found a disclaimer for the conjecture!
-
return False
-
#for each element in list of evens
-
for i in evens:
-
if expressAsSum(i) == False:
-
print (str(i) + “fails Goldbach’s Conjecture”)
-
break
-
for iNum,i in enumerate(evens):
-
print (“%d = %d + %d” % (i, sums[2*iNum], sums[2*iNum+1]))
Eric
July 5, 2013 at 9:00 pm
Hi it’s Eric again, I was just wondering why Russel’s entry was chosen the winner but my code is the one that’s been posted here.
downhousesoftware
July 5, 2013 at 9:20 pm
Crap – I’m sorry about that Eric. I didn’t mean to misattribute. I’m sending you a person email as well, please comment again here or write to me directly if you do not receive it within the hour.
Sincerely,
Jack
Eric
July 6, 2013 at 12:22 am
Thanks for the fix! 🙂