Project-Euler-002

Problem

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.

Answer

1
4613732

python

1
2
3
4
5
6
7
8
9
10
11
12
def compute():
ans = 0
x = 1 # Represents the current Fibonacci number being processed
y = 2 # Represents the next Fibonacci number in the sequence
while x <= 4000000:
if x % 2 == 0:
ans += x
x, y = y, x + y
return str(ans)

if __name__ == "__main__":
print(compute())


JavaScript

1
2
3
4
5
6
7
let s = 0
let f = [1, 1]
while (f[0] < 4e6) {
if (f[0] % 2 === 0) s+= f[0]
f = [f[1], f[0]+f[1]]
}
console.log(s)


Ruby

1
2
3
4
5
6
7
#!/usr/bin/env ruby
sum a, b = 0, 1, 2
while b < 4000000
sum += b if b.even?
a, b = b, a+b
end
puts sum


Go

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
sum := 0
for a, b := 1, 2; b <= 4e6; a, b = b, a+b {
if b%2 == 0 {
sum += b
}
}
fmt.Println(sum)
}


Haskell

1
2
3
4
5
fibs :: [Integer]
fibs = 0:1:zipWith (+) fibs (tail fibs)

main :: IO()
main = print $sum $ filter even $ takeWhile (<4000000) fibs


Clojure

1
2
3
#!/usr/bin/env clojure
(def fibs (lazy-cat [0 1] (map + (rest fibs) fibs)))
(println (reduce + (filter even? (take-while #(< % 4000000) fibs))))


Mathematica

1
2
3
4
5
s = 0;
For[i = 0, (f = Fibonacci[i]) <= 4000000, i++,
If[EvenQ[f],
s += f]]
s


Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public final class p002 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p002().run());
}


/*
* Computers are fast, so we can implement this solution directly without any clever math.
* Because the Fibonacci sequence grows exponentially by a factor of 1.618, the sum is
* bounded above by a small multiple of 4 million. Thus the answer fits in a Java int type.
*/
public String run() {
int sum = 0;
int x = 1; // Represents the current Fibonacci number being processed
int y = 2; // Represents the next Fibonacci number in the sequence
while (x <= 4000000) {
if (x % 2 == 0)
sum += x;
int z = x + y;
x = y;
y = z;
}
return Integer.toString(sum);
}

}

文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/02/09/Project-Euler-002/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏