Project Euler その1

Pythonで解いてみた。

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

 10以下のすべての自然数のうち3か5の倍数の数字を並べると、3,5,6,9が得られる。これらの数の和は23である。1000以下の3か5の倍数の総和を求めよ。

コード
s = 0

for i in range(1, 1000):
    if i % 15 == 0:
        print i,
        s += i
    else:
        if i % 5 == 0:
            print i,
            s += i
        if i % 3 == 0:
            print i,
            s += i

print s

何のことはなく正解。

Problem 2

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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

 フィボナッチ数列の要素は前の2つの要素から生成される。1と2から始めると、最初の10個までの数列は1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...のようになる。数列の要素の値が400万を超えないフィボナッチ数列を考えた時、そのうちの偶数の総和を求めよ。

even-valuesって偶数を意味するのか・・・

コード
from math import sqrt

a = (1+sqrt(5))/2
b = (1-sqrt(5))/2
r = 0

i = 1
s = 0
while 1:
    r = int((1/sqrt(5))*(a**i-b**i))
    if r>=4000000: break
    if r%2 == 0:
        s += r
    i+=1
print s

ちょっと変な方法で解いた。ビネの公式を用いてフィボナッチ数列の各項を出してる。