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:
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
Clojure
#!/usr/bin/env clojure
(def fibs (lazy-cat [0 1] (map + (rest fibs) fibs)))
(println (reduce + (filter even? (take-while #(< % 4000000) fibs))))
Go
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
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
main :: IO ()
main = print $ sum $ filter even $ takeWhile (<4000000) fibs
JavaScript
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
#!/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