Problem 2: 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.

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)
}

Cookies

This site uses cookies when:

If you use only Open Source products, sorry about using cookies, I will replace Disqus as my comments platform in the future.

If you use private source products, worrying about privacy and using this products is like worrying about global warming and not recycling.. So just don’t do it.. 😒