Find the sum of the even Fibonacci numbers up to 4 million.
Solution
Calculating the Fibonacci numbers is straightforward and requires minimal memory, as we only have to keep track of the current number and the previous two numbers. Checking if a number is even is as simple as dividing by 2 and looking for a remainder of 0.
package main
import "fmt"
func main() {
sum := 0
sequence := [3]int{1, 1, 2}
for sequence[2] <= 4000000 {
// Check if current number is even
if sequence[2]%2 == 0 {
sum += sequence[2]
}
// Move all numbers back one space,
// then recalculate current number
sequence[0] = sequence[1]
sequence[1] = sequence[2]
sequence[2] = sequence[0] + sequence[1]
}
fmt.Println(sum)
}
An alternative method, to remove the modulus operation, would be to check if the last digit is 0, 2, 4, 6 or 8. However, division by 2 is usually something that a compiler can optimise to something other than a DIV instruction.