w3resource logo


Euler Project

Project Euler solution: Even Fibonacci numbers

Secondary Nav

Problem - 2

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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Result : 4613732

Solution in multiple languages

PHP

<?php
$x = 2;
$y = 1;
$sum = 2;
$n = 0;
while ($n < 4000000) 
{
 $n = $x + $y;
 $y = $x;
 $x = $n;
 if (!($n % 2)) 
 {
  $sum += $n;
 }
 }
 echo $sum;
?>

Python

cache = {}
def fiba(n):
     cache[n] = cache.get(n, 0) or (n <= 1 and 1 or fiba(n-1) + fiba(n-2))
     return cache[n]
n = 0
x = 0
while fiba(x) <= 4000000:
       if not fiba(x) % 2: n = n + fiba(x)
       x=x+1
print(n)

Java

public final class eu_p002_sol {

	public static void main(String[] args) {
		System.out.println(new eu_p002_sol().run());
	}
public String run() {
		int sum = 0;
		for (int x = 0; ; x++) {
			int fib = fibonacci(x);
			if (fib > 4000000)
				break;
			if (fib % 2 == 0)
				sum += fib;
		}
		return Integer.toString(sum);
	}

	private static int fibonacci(int n) {
		if (n < 0 || n > 46)
			throw new IllegalArgumentException();
		int a = 0;
		int b = 1;
		for (int i = 0; i < n; i++) {
			int c = a + b;
			a = b;
			b = c;
		}
		return a;
	}
}

Ruby

#!/usr/bin/env ruby
sum, x, y = 0, 1, 2
while y < 4000000
  sum += y if y.even?
  x, y = y, x + y
end
puts sum

C

#include <stdio.h>
int main(void)
{
  unsigned int zx1 = 1, zx2 = 1, zx3 = 2, zsum = 0;
  while (zx3 < 4000000)
 {
    zx3 = zx1 + zx2;
    zsum += zx3 * !(zx3%2);
    zx1 = zx2;
    zx2 = zx3;
  }
  printf("%u\n", zsum);
  return 0;
}

JavaScript

function solution()
 {
    var fibno = [ 1, 2 ], sum = 0;

 function cal(arr )
  {
   return arr[ arr.length - 1 ] + arr[ arr.length - 2 ];
 }

  while ( fibno[ fibno.length - 1 ] < 4e+6 )
    {
      fibno.push( cal(fibno) );
    }

    fibno.forEach( function(n) 
     {
        if ( n % 2 === 0 )
        {
            sum += n;
        }
    });
    return sum;
}

console.log(solution())

Go

package main

func main() {
    x, y, sum := 1, 2, 0
    for y < 4000000 {
        if y%2 == 0 {
            sum += y
        }
        x, y = y, x+y
    }
    println(sum)
}


Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number