I started Jon Calhoun's Algorithms With Go course this week, and I have to say it's very enjoyable. I don't know whether it's the course content or getting my hands dirty writing Go Code but it really is a great course.
Anyhoo - One of the algorithms included in the course is the calculation of the Fibonacci sequence.
The Fibonacci sequence is defined as
or
F(n) = F(n-1) + F(n-2)
I wrote the following solution (here's one I made earlier), but it's bothering me because I feel like it could be written in even less lines of code. Anyone care to try?
I'm not expecting Go, feel free to write it in any language you see fit, I'm just curious how compact the solution to a challenge like this can be. What better community to ask than the dev.to community?
func Fibonacci(n int) int {
if n < 1 {
return 0
}
if n < 3 {
return 1
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
Top comments (3)
Rust Solution
I like doing Fib iteratively cause š¤· So here is my iterative fib, and a version that returns a list of the fib numbers. With the iterative answer that is a pretty simply modification!
play.rust-lang.org/?version=stable...
Haskell (the classic solution):
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Then: take 10 fibs
This was pretty much exactly what I was looking for. To be completely honest, I knew some functional language would swoop in with a one liner