Do you know the optimal solution?

Do you know the optimal solution?

The Fibonacci sequence is one of the most famous patterns in mathematics. Each term is built from the previous two terms with two base cases to begin the pattern. The first base case value is zero, and the second value is one. From here, we can calculate any Fibonacci number using the following formula:

Fibonacci(n)=Fibonacci(n-1)+Fibonacci(n-2)

The Fibonacci sequence makes for a perfect question to test your fundamental computer science knowledge and coding skills. In this article we will go over three examples of how to calculate the nth Fibonacci number using the programming language Go while being as efficient as possible.

**Note:** This tutorial assumes knowledge of recursion and the stack data structure.

Let’s code!

An initial naive solution is to directly translate the formula for the nth Fibonacci sequence into code. All we have to do are check if we are at a base case for `n==1`

or `n==2`

, if not we recursively return `fib()`

with the parameters `n-1`

and `n-2`

. Seriously, this solution is clean and concise!

```
func fib(n int) int {
if n == 2 {
return 1
} else if n == 1 {
return 0
}
return fib(n-1) + fib(n-2)
}
```

Golang Web Development is the new trend globally. Get all the details about the Golang development here. Hire Golang Developers.

With transformational changes seen in the business and technology front, Entrepreneurs’ view towards technologies is changing. Here are [the top technologies that young entrepreneurs can embed to increase their business...

Hire dedicated GoLang developers from WebClues Infotech to build applications using Go language. Get best GoLang developers for your web development projects.

Asynchronous - Async programming - Untangled . In the recent times there has been an increased emphasis on building high performance application which can perform better at scale to…

Get updated with the newest top 10 trending technologies in 2021 which professional must learn to boost there career.