From acd90b8221320a64a380b815580b406ca1fd6d6b Mon Sep 17 00:00:00 2001 From: VicRen Date: Thu, 1 Oct 2020 15:09:06 +0800 Subject: [PATCH] Project Euler #2: Even Fibonacci numbers --- fibonacci/README.md | 6 +++ fibonacci/fibonacci_test.go | 77 +++++++++++++++++++++++++++++++++++++ fibonacci/main.go | 35 +++++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 fibonacci/README.md create mode 100644 fibonacci/fibonacci_test.go create mode 100644 fibonacci/main.go diff --git a/fibonacci/README.md b/fibonacci/README.md new file mode 100644 index 0000000..e10afe7 --- /dev/null +++ b/fibonacci/README.md @@ -0,0 +1,6 @@ +# 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. \ No newline at end of file diff --git a/fibonacci/fibonacci_test.go b/fibonacci/fibonacci_test.go new file mode 100644 index 0000000..6d6b5b3 --- /dev/null +++ b/fibonacci/fibonacci_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestGetFibonacciTill(t *testing.T) { + tt := []struct { + name string + input int + want []int + }{ + { + "till 1", + 1, + []int{1}, + }, + { + "till 2", + 2, + []int{1, 2}, + }, + { + "till 3", + 3, + []int{1, 2, 3}, + }, + { + "till 100", + 100, + []int{1, 2, 3, 5, 8, 13, 21, 34, 55, 89}, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := GetFibonacciTill(tc.input) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("GetFibonacciTill(%d)=%v, want %v", tc.input, got, tc.want) + } + }) + } +} + +func TestIsEvenValue(t *testing.T) { + tt := []struct { + name string + input int + want bool + }{ + { + "1", + 1, + false, + }, + { + "2", + 2, + true, + }, + { + "100", + 100, + true, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := IsEvenValue(tc.input) + if got != tc.want { + t.Errorf("IsEvenValue(%d)=%v, want %v", tc.input, got, tc.want) + } + }) + } +} diff --git a/fibonacci/main.go b/fibonacci/main.go new file mode 100644 index 0000000..6bf800d --- /dev/null +++ b/fibonacci/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" +) + +func main() { + end := 4000000 + nums := GetFibonacciTill(end) + fmt.Println("the fibonacci below 4000000 is", nums) + sum := 0 + for _, n := range nums { + if IsEvenValue(n) { + sum += n + } + } + fmt.Println("event-value sum of numbers in 4000000 is", sum) +} + +func GetFibonacciTill(n int) []int { + var ret []int + next := 1 + last := 1 + for next <= n { + add := next + ret = append(ret, add) + next += last + last = add + } + return ret +} + +func IsEvenValue(n int) bool { + return n%2 == 0 +}