Problem 2: Even Fibonacci numbers

Coding challenges are a great resource for learning coding techniques and improve analytical thinking, this is a collection of challenges from different platforms.

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.

Sample 00

input00.txt
10
output00.txt
10

Sample 01

input01.txt
4000000
output01.txt
4613732

Solution

main.go
package main

import (
  "fmt"
)

func main() {
  var (
    n, r int
  )

  fmt.Scan(&n)

  n1, n2, n3 := 1, 1, 2
  for n3 < n {
    r += n3
    n1 = n2 + n3
    n2 = n1 + n3
    n3 = n1 + n2
  }

  fmt.Println(r)
}