# Solutions for Problem 2

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.

## PL/SQL by mmaster

Runtime: 0.06s

``` DECLARE
i       INTEGER;
j       INTEGER;
k       INTEGER;
total   INTEGER;
maximum constant INTEGER := 4000000;
BEGIN
i      := 1;
j      := 1;
k      := 0;
total  := 0;
WHILE i < maximum
LOOP
IF (i mod 2) = 0 THEN
total     := total + i;
END IF;
k := j;
j := i + j;
i := k;
END LOOP;
dbms_output.put_line (total);
END;
```

## python by astan (traltixx)

Runtime: 0.03s

```   import time
start_time = time.time()
def tfib(limit):
a, b = 0, 1
t = 0
i = 0
while a < limit:
a, b = b, a+b
if a%2 == 0:
t+=a
print a
i+=1
return t
limit = 4000000
print tfib(limit)
run_time = time.time() - start_time
print 'Run time: %f seconds' % run_time
```

## C++ by Tina (tinang)

```  #include <iostream>

using namespace std;

int main(int argv, char* argc[])
{
int x = 1;
int y = 2;
int sum = 0;
if(x%2==0)
sum = sum + x;
else if(y%2==0)
sum = sum + y;
while (x <= 4000000 || y <= 4000000)
{
x = x + y;
y = y + x;
if(x%2==0)
sum = sum + x;
else if(y%2==0)
sum = sum + y;
}
cout << sum << endl;
return 0;
}
```

Runtime: 8.603 ms

```{- Fibonacci numbers -}
fibs :: [Integer]
fibs = 1:1:fibs'
where
fibs' = zipWith (+) fibs (tail fibs)

{- Sum the even fibonacci numbers less than 4 million. -}
main = print (sum (filter (\x -> mod x 2 == 0) (takeWhile (< 4000000) fibs)))
```

## Caml by SanguineV

Runtime: 10.631 ms

```(* Generate fibonacci numbers less than a limit *)
let fibsToN n =
let rec inner f1 f2 =
let f3 = f1 + f2 in
if f3 > n
then f1 :: [f2]
else f1 :: inner f2 f3
in
inner 1 1
;;

{- Print the sum of the even Fibonacci numbers less than 4 million. -}
Printf.printf "Total: %u\n" (List.fold_left (+) 0
(List.filter (fun x -> x mod 2 == 0) (fibsToN 4000000)))
```

## Ruby by tomchristmas

Runtime: 27ms

```fib = [1,1]
fib.push(fib[fib.length - 1] + fib[fib.length - 2]) while fib.last < 4000000
fib.pop
puts fib.inject(0){|x,y| (y % 2 == 0) ? x + y : x}

```

## C by ctd

Runtime: 4ms

```#include <stdio.h>

int main (int argc, char* argv[])
{
int seq[] = { 2, 3, 5 };
int sum = 2;
while (seq[2] <= 4000000) {
int i;
for (i = 1; i <= 2; i++) seq[i-1] = seq[i];
seq[2] = seq[0] + seq[1];
if (seq[2] % 2 == 0) sum += seq[2];
}
printf("%d\n", sum);
return 0;
}
```

## Java by knockycode

```public static void main(String[] args)
{
int temp, x = 0, y = 1, total = 0;
while (y < 4000000)
{
temp = y;
y += x;
x = temp;
if (y % 2 == 0) total += y;
}
System.out.println(total);
}
```