Project Euler 2: (Iron)Python

Posted by Ben Griswold on Johnny Coder See other posts from Johnny Coder or by Ben Griswold
Published on Mon, 13 Sep 2010 00:08:20 +0000 Indexed on 2010/12/06 16:59 UTC
Read the original article Hit count: 378

In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 2

As always, any feedback is welcome.

# Euler 2
# http://projecteuler.net/index.php?section=problems&id=2
# Find the sum of all the even-valued terms in the
# Fibonacci sequence which do not exceed four million.
# Each new term in the Fibonacci sequence is generated
# by adding the previous two terms. By starting with 1
# and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# Find the sum of all the even-valued terms in the
# sequence which do not exceed four million.
import time
start = time.time()

total = 0
previous = 0
i = 1

while i <= 4000000:
    if i % 2 == 0: total +=i

    # variable swapping removes the need for a temp variable
    i, previous = previous, previous + i

print total 

print "Elapsed Time:", (time.time() - start) * 1000, "millisecs"
a=raw_input('Press return to continue')

© Johnny Coder or respective owner

Related posts about ironpython

Related posts about languages