Project Euler: Even Fibonacci Numbers

go
r
python
project euler
puzzle
Find the sum of even Fibonacci numbers less than 4 million.
Author

Stephen Feagin

Published

October 5, 2022

Onward to Project Euler problem 2: Even Fibonacci Numbers. The brief reads:

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.

Solution

My approach is the same across all three languages. Starting after the first two values in the sequence, keep track of the running sum and the most recent two values. Calculate the next term in the series by adding the previous two. While the new term is less than 4 million, check if it’s even. If it is, add it to the running total. Update the last two terms and calculate the next term, then run through the loop again.

R

# Keep track of the most recent two terms
last_two <- c(1, 2)
# Running total sum
# Start with 2 because it's already in the first two terms
total <- 2
# Get the next term in the sequence
next_term <- sum(last_two)
while (next_term < 4e6) {
    if (next_term %% 2 == 0) {
        total <- total + next_term
    }
    last_two <- c(last_two[2], next_term)
    next_term <- sum(last_two)
}
total
[1] 4613732

Python

# Start with the first two terms
# The sum of the even numbers is already 2
total = 2
# Keep track of the most recent two numbers
last_two = [1, 2]
# Get the next term in the sequence, the sum of the previous two terms
next_term = sum(last_two)
while next_term < 4000000:
    # If the new term is even, add it to the running total
    if next_term % 2 == 0:
        total += next_term
    # Update the last_two list
    last_two = [last_two[1], next_term]
    next_term = sum(last_two)
print(total)
4613732

Go

// Keep track of the running total, starting with two because we start looping
// after the first two terms
total := 2
// Keep track of the previous two values
lastTwo := []int{1, 2}
// Get the next term in the sequence by adding the previous two
nextTerm := lastTwo[0] + lastTwo[1]
for nextTerm < 4000000 {
    // If the new term is even, add it to the running total
    if nextTerm%2 == 0 {
        total += nextTerm
    }

    // Update the lastTwo slice
    lastTwo = []int{lastTwo[1], nextTerm}

    // Update the nextTerm value
    nextTerm = lastTwo[0] + lastTwo[1]
}
fmt.Println(total)

See all of my Project Euler solutions on GitHub.