Skip to content

Commit 98add67

Browse files
Add fibonacci algorithm by dynamic programming (#252)
* Add fibonacci algorithm by dynamic programming * Improve fibonacci.go implementation * Add test for NthFibonacci function * Put the test runs inside test cases loop
1 parent f6b4606 commit 98add67

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

dynamicprogramming/fibonacc_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package dynamicprogramming
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func Test_NthFibonacci(t *testing.T) {
9+
// source: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
10+
var fibonacciNumbers = []struct {
11+
nth uint
12+
fibonacci uint
13+
}{
14+
{0, 0},
15+
{1, 1},
16+
{2, 1},
17+
{3, 2},
18+
{4, 3},
19+
{5, 5},
20+
{6, 8},
21+
{7, 13},
22+
{8, 21},
23+
{9, 34},
24+
{10, 55},
25+
{20, 6765},
26+
{30, 832040},
27+
{40, 102334155},
28+
{50, 12586269025},
29+
{60, 1548008755920},
30+
{70, 190392490709135},
31+
{80, 23416728348467685},
32+
{90, 2880067194370816120},
33+
}
34+
for i := range fibonacciNumbers {
35+
t.Run(fmt.Sprintf("the %dth Fibonacci number", fibonacciNumbers[i].nth), func(t *testing.T) {
36+
result := NthFibonacci(fibonacciNumbers[i].nth)
37+
if result != fibonacciNumbers[i].fibonacci {
38+
t.Errorf("Expected the %dth Fibonacci number to be %d, got %d", fibonacciNumbers[i].nth, fibonacciNumbers[i].fibonacci, result)
39+
}
40+
})
41+
}
42+
}

dynamicprogramming/fibonacci.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package dynamicprogramming
2+
3+
// https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
4+
5+
// NthFibonacci returns the nth Fibonacci Number
6+
func NthFibonacci(n uint) uint {
7+
if n == 0 {
8+
return 0
9+
}
10+
11+
// n1 and n2 are the (i-1)th and ith Fibonacci numbers, respectively
12+
var n1, n2 uint = 0, 1
13+
14+
for i := uint(1); i < n; i++ {
15+
n3 := n1 + n2
16+
n1 = n2
17+
n2 = n3
18+
}
19+
20+
return n2
21+
}

0 commit comments

Comments
 (0)