Tim Varley Logo
Tim Varley Systems Engineer
Problem #2 easy

Even Fibonacci Numbers

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.

Algorithm Insights

This problem introduces the Fibonacci sequence and requires summing only the even-valued terms. The key insight is that every third Fibonacci number is even, which can lead to more efficient solutions, but the iterative approach shown here works well for the given constraints.

Implementations

#include <iostream>
int main(int argc, char* argv[])
{
unsigned long long sum = 0;
unsigned long long a = 1, b = 2;
while (b <= 4000000) {
if (b % 2 == 0) {
sum += b;
}
unsigned long long temp = a + b;
a = b;
b = temp;
}
std::cout << sum << std::endl;
return 0;
}
public class Euler002 {
public static void main(String[] args) {
long sum = 0;
long a = 1, b = 2;
while (b <= 4000000) {
if (b % 2 == 0) {
sum += b;
}
long temp = a + b;
a = b;
b = temp;
}
System.out.println(sum);
}
}
function fibonacciEvenSum(limit) {
let sum = 0;
let a = 1, b = 2;
while (b <= limit) {
if (b % 2 === 0) {
sum += b;
}
let temp = a + b;
a = b;
b = temp;
}
return sum;
}
console.log(fibonacciEvenSum(4000000));
<?php
$sum = 0;
$a = 1;
$b = 2;
while ($b <= 4000000) {
if ($b % 2 == 0) {
$sum += $b;
}
$temp = $a + $b;
$a = $b;
$b = $temp;
}
echo $sum;
?>
def fibonacci_even_sum(limit)
sum = 0
a, b = 1, 2
while b <= limit
sum += b if b.even?
a, b = b, a + b
end
sum
end
puts fibonacci_even_sum(4_000_000)
package main
import "fmt"
func main() {
var sum int64 = 0
a, b := int64(1), int64(2)
for b <= 4000000 {
if b%2 == 0 {
sum += b
}
a, b = b, a+b
}
fmt.Println(sum)
}
fn main() {
let mut sum: u64 = 0;
let mut a: u64 = 1;
let mut b: u64 = 2;
while b <= 4_000_000 {
if b % 2 == 0 {
sum += b;
}
let temp = a + b;
a = b;
b = temp;
}
println!("{}", sum);
}