To find the nth Fibonacci number in Go, we can use either recursion or dynamic programming approach.
Recursion is a simple approach to find the nth Fibonacci number. We can write a function that calls itself repeatedly until it reaches the base case. The base case is when n is either 0 or 1, then we return n. Otherwise, we recursively call the function for n-1 and n-2, and return their sum.
main.go149 chars7 lines
Dynamic Programming is an efficient approach to find the nth Fibonacci number. We can store the previously calculated Fibonacci numbers in an array and use them to calculate the new number. We can initialize the first two Fibonacci numbers as 0 and 1, respectively, and then iterate from 2 to n, calculating the new Fibonacci number by adding the previous two.
main.go228 chars13 lines
Both approaches have a time complexity of O(n) and a space complexity of O(n) because we need to store the previously calculated Fibonacci numbers.
gistlibby LogSnag