2010年2月18日木曜日

problem2 in python


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.



自分の解答


def fib(n):
list = range(3)
if n ==1 or n == 2 or n == 3:
return n
for i in range(n):
if not(i == 0 or n == 1 or i == 1):
if(list[i]+list[i-1]) >4000000:
break
list.append(list[i]+list[i-1])
list.remove(0)
return list
sum = 0
ans = fib(400000)
for j in ans:
if j %2 == 0:
print j
sum +=j
print sum

0 件のコメント:

コメントを投稿