Commits

Shu Zong Chen committed 67f2920

solved problem 2

Comments (0)

Files changed (1)

+/*
+Problem 2:
+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.
+*/
+package main
+
+import (
+	"fmt"
+)
+
+func fibonacci_generator() chan int {
+	ch := make(chan int)
+	go func() {
+		i := 1
+		p := 0
+		for {
+			ch <- i
+			i = i + p
+			p = i - p
+		}
+	}()
+	return ch
+}
+
+func run(limit int){
+	sum := 0
+	ch := fibonacci_generator()
+	for {
+		fib := <-ch
+		if fib >= limit{
+			break
+		}
+		if fib % 2 == 0{
+			sum += fib
+		}
+	}
+	fmt.Printf("%d\n", sum)
+}
+
+func main(){
+	run(4000000)
+}
+