mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-30 18:18:45 +01:00
Project Euler #2: Even Fibonacci numbers
This commit is contained in:
@@ -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.
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user