Question
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.
Clojure
#!/usr/bin/env clojuredef fibs (lazy-cat [0 1] (map + (rest fibs) fibs)))
(println (reduce + (filter even? (take-while #(< % 4000000) fibs)))) (
$ time clojure fibonacci.clj
real 0m0.885s
user 0m1.720s
sys 0m0.092s
Go
package main
import "fmt"
func main() {
:= 0
sum for a, b := 1, 2; b <= 4e6; a, b = b, a+b {
if b%2 == 0 {
+= b
sum }
}
.Println(sum)
fmt}
$ go build -o fibonacci fibonacci.go
$ time ./fibonacci
real 0m0.001s
user 0m0.000s
sys 0m0.001s
Haskell
fibs :: [Integer]
= 0 : 1 : zipWith (+) fibs (tail fibs)
fibs
main :: IO ()
= print $ sum $ filter even $ takeWhile (<4000000) fibs main
$ ghc -O2 -o fibonacci fibonacci.hs
$ time ./fibonacci
real 0m0.002s
user 0m0.000s
sys 0m0.002s
JavaScript
let s = 0
let f = [1, 1]
while (f[0] < 4e6) {
if (f[0] % 2 === 0) s+= f[0]
= [f[1], f[0] + f[1]]
f
}console.log(s)
$ time node --use-strict fibonacci.js
real 0m0.052s
user 0m0.030s
sys 0m0.023s
Ruby
#!/usr/bin/env ruby
= 0, 1, 2
sum, a, b while b < 4000000
+= b if b.even?
sum = b, a + b
a, b end
puts sum
$ time ruby fibonacci.rb
real 0m0.038s
user 0m0.038s
sys 0m0.000s
Rust
fn main() {
let mut sum = 0;
let mut a = 1;
let mut b = 2;
let mut tmp;
while b <= 4000000 {
if b % 2 == 0 {
+= b;
sum }
= a + b;
tmp = b;
a = tmp;
b }
println!("{}", sum);
}
$ rustc -C target-cpu=native -C opt-level=3 -o fibonacci fibonacci.rs
$ time ./fibonacci
real 0m0.001s
user 0m0.000s
sys 0m0.001s