Mathematician Leonardo Fibonacci posed this problem: “How many pairs of rabbits will be produced in a year, beginning with a single pair, if in every month each pair bears a new pair which becomes productive from the second month on?” The function for this problem is:
1 2 3 4
IF n < 3: F(n) = 1 ELSE: F(n) = F(n-1) + F(n-2)
Solutions
A simple recursive algorithm.
1 2 3 4 5 6 7
funcFibOne(n int)int { if n < 3 { return1 }
return FibOne(n-1) + FibOne(n-2) }
Benchmark this solution, run 10 times to calculate Fibonacci number 10
1
go test -v ./tests/ -bench=BenchmarkFibOne -count=10 -run=none
The solution one is simple and easy to understand this problem. It has a good performance if the number smaller than 50. While when set a bigger number the job is very slow.
1
go run main.go -n 100
The output is similar as:
1 2 3
2022-01-13 12:03:55.114728|solutions.algorithms/fibonacciNumber/solutions.FibOne(100) -> out of time :( 2022-01-13 12:03:55.114848|solutions.algorithms/fibonacciNumber/solutions.FibTwo(100) -> 3736710778780434371 2022-01-13 12:03:55.114900|solutions.algorithms/fibonacciNumber/solutions.FibThree(100) -> 3736710778780434371
The solution two is an improvement based on the solution one. It is hard to think if without the fib tree images. From above result, it is faster than before one.
The solution three using a map data in memory reduce the calculation steps. The recursive structure make it is easy to understand. From benchmark testing it has a better performance than above two solutions.