Problem 2
Ruby
1sum_even = 0;
2term_prev = 1;
3term_current = 1;
4loop do
5 if term_current >= 4000000
6 break
7 end
8 temp = term_current;
9 term_current = term_current + term_prev;
10 term_prev = temp;
11 if term_current % 2 == 0
12 sum_even += term_current;
13 end
14end
15puts "#{sum_even}"
Clojure
1(ns problem2.core)
2;generate a list of the fibonacci numbers
3(def gen-fib
4 (lazy-cat [0 1] (map + (rest gen-fib) gen-fib)))
5
6(defn -main
7 []
8 (println (reduce + (filter even? (take-while (partial > 4000000) gen-fib)))))
Perl 6
1say (1, 1, *+ *... ^*> 4000000 ).grep( * %% 2 ).sum;
Java
1class FibSum{
2 public static void main(String args[]){
3 double prevTerm = 1;
4 double curTerm = 1;
5 double tempTerm;
6 int sum = 0;
7 while(curTerm < 4000000){
8 tempTerm = curTerm;
9 curTerm = prevTerm + curTerm;
10 prevTerm = tempTerm;
11 if(curTerm % 2 == 0){
12 sum += curTerm;
13 }
14 }
15 System.out.printf("%d\n", sum);
16 }
17}