Skip to content

Commit a0567e6

Browse files
committed
Inital code commit
1 parent d407c87 commit a0567e6

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

fib.go

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package fib
2+
3+
import "math/big"
4+
5+
// Fibonacci calculates Fibonacci number.
6+
// This function generated correct values from 0 to 93 sequence number.
7+
// For bigger values use FibonacciBig function
8+
func Fibonacci(n uint) uint64 {
9+
if n <= 1 {
10+
return uint64(n)
11+
}
12+
13+
var n2, n1 uint64 = 0, 1
14+
15+
for i := uint(2); i < n; i++ {
16+
n2, n1 = n1, n1+n2
17+
}
18+
19+
return n2 + n1
20+
}
21+
22+
// FibonacciBig calculates Fibonacci number using bit.Int.
23+
// For the sequence numbers below 94, it is recommended to use Fibonacci function.
24+
func FibonacciBig(n uint) *big.Int {
25+
if n <= 1 {
26+
return big.NewInt(int64(n))
27+
}
28+
29+
var n2, n1, tmp = big.NewInt(0), big.NewInt(1), big.NewInt(0)
30+
31+
for i := uint(1); i < n; i++ {
32+
tmp.Set(n1)
33+
n1.Add(n1, n2)
34+
n2.Set(tmp)
35+
}
36+
37+
return n1
38+
}

fib_test.go

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package fib
2+
3+
import "testing"
4+
5+
func BenchmarkFibonacci_10(b *testing.B) {
6+
for i := 0; i < b.N; i++ {
7+
Fibonacci(10)
8+
}
9+
}
10+
11+
func BenchmarkFibonacci_20(b *testing.B) {
12+
for i := 0; i < b.N; i++ {
13+
Fibonacci(20)
14+
}
15+
}
16+
17+
func BenchmarkFibonacciBig_10(b *testing.B) {
18+
for i := 0; i < b.N; i++ {
19+
FibonacciBig(10)
20+
}
21+
}
22+
23+
func BenchmarkFibonacciBig_20(b *testing.B) {
24+
for i := 0; i < b.N; i++ {
25+
FibonacciBig(20)
26+
}
27+
}
28+
29+
func TestFibonacci(t *testing.T) {
30+
data := []struct {
31+
n uint
32+
want uint64
33+
}{
34+
{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}, {10, 55}, {42, 267914296},
35+
}
36+
37+
for _, d := range data {
38+
if got := Fibonacci(d.n); got != d.want {
39+
t.Errorf("Invalid Fibonacci value for N: %d, got: %d, want: %d", d.n, got, d.want)
40+
}
41+
}
42+
}
43+
44+
func TestFibonacciBig(t *testing.T) {
45+
data := []struct {
46+
n uint
47+
want int64
48+
}{
49+
{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}, {10, 55}, {42, 267914296},
50+
}
51+
52+
for _, d := range data {
53+
if got := FibonacciBig(d.n); got.Int64() != d.want {
54+
t.Errorf("Invalid Fibonacci value for N: %d, got: %d, want: %d", d.n, got, d.want)
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)