Without a Traceroute

Time to live.

Without a Traceroute header image 2

Project Euler

December 23rd, 2008 · 3 Comments · Coding, Germany

I arrived in Frankfurt after a pretty miserable overnight train ride. The compartment I was in also had a family with two small children. I’ve also developed a painful sore throat in the last few days. Between the kids and the throat, I wasn’t getting any sleep anyway, so I hid out in the restaurant car, chain-drinking teas (and burning through the last of my Polish zloty), reading and coding.

A while back, my friend Nick introduced me to Project Euler, which is a really cool (well, not really cool, but nerd-cool, which is better anyway) collection of little mathematical puzzles that are best solved through the application of computer programming.

I’ve been looking to learn Python for a while now, so I decided to start working through some of the Project Euler problems as a way to learn Python. I did the first two on the train: summing all natural multiples of 3 or 5 below 1,000, and summing the even Fibonacci numbers below 4 million.

If you care, my code is below:

Somebody told me this code is a bit counter-intuitive and hard to read, which might be true. I tried to use as few variables (two), loops (one) and iterations (only 333 rather than 999) as possible.

j = 0
count = 0
while 3*j < 1000:

if 5*j < 1000 and int(((5*j)/ 3.0)) != ((5*j)/ 3.0):

count = count + 3*j + 5*j

else:

count = count + 3*j

j = j + 1

print “This program sums all the natural numbers below 1,000 that are multiples of 3 or 5:”, count

Same story here, there’s more self-evident ways to code the Fibonacci sequence. One of my friends told me that in Python, you can assign two variables in one line so you could just do “a, b = a+b, a”, but I didn’t know that, so this is what I did. I thought using the transitive property of addition rather than introducing another variable was at least slightly clever:

a = 1
b = 1
total = 0

while b < 4000000:

if int(b/2.0) == b/2.0:

total = total + b

a = a + b
b = a – b

print total

Tags:

3 Comments so far ↓

Leave a Comment